如何在Angular 13的类组件内创建一个函数?

huangapple go评论72阅读模式
英文:

how to create a function inside the class component in angular 13?

问题

我有一个用于切换开关的代码,但问题是我无法摆脱错误,它说'意外标记',它期望在类内的构造函数或方法。这是Angular组件和需要实现的类,我不需要其他文件来实现,只需要这两个实现,以下是我尝试过的内容。

// Angular js 13中的代码
import { Component } from '@angular/core';

@Component({
  selector: 'toggle-button',
  template: `
    <div class="toggle-button">
      <button (click)="toggleState()">{{ yourVariableName === true ? "ON" : "OFF" }}</button>
    </div>
  `
})

export class ToggleButton {
  buttonState: boolean = false;

  toggleState() {
    this.buttonState = !this.buttonState;
  }
}

图片描述

英文:

I have code for switch toogle but the problem i cant get rid of the erro says 'unexpected token' its expecting constructor or method within a class. This is Angular component and class that needs to be implements i dont need other files to use to achieve only these two implementation and below this is what i tried.

`// code in Angular js 13
import { Component} from &#39;@angular/core&#39;;

@Component({
selector: &#39;toggle-button&#39;,
template: `
&lt;div class=&quot;toggle-button&quot;&gt;
    &lt;button (click)=&quot;toggleState()&quot;&gt;{{ yourVariableName === true ? &quot;ON&quot; : &quot;OFF&quot; }} /&gt;
&lt;/div&gt;
`})

export class ToggleButton {
    buttonState: boolean = false;

    function toggleState() {
        this.buttonState != this.buttonState;
    }
}`
```[enter image description here][1]


  [1]: https://i.stack.imgur.com/0sgd8.png

</details>


# 答案1
**得分**: 0

将您的模板从以下内容进行修改:

```html
&lt;div class=&quot;toggle-button&quot;&gt;
    &lt;button (click)=&quot;toggleState()&quot;&gt;{{ yourVariableName === true ? &quot;ON&quot; : &quot;OFF&quot; }} /&gt;
&lt;/div&gt;

修改为:

&lt;div class=&quot;toggle-button&quot;&gt;
    &lt;button (click)=&quot;toggleState()&quot;&gt;{{ yourVariableName === true ? &quot;ON&quot; : &quot;OFF&quot; }}&lt;/button&gt;
&lt;/div&gt;

您在按钮的起始和结束标签方面出现了问题。文本 "ON" 和 "OFF" 应该位于两个按钮标签之间:&lt;button&gt;&lt;/button&gt;

英文:

Modify your template from this:

&lt;div class=&quot;toggle-button&quot;&gt;
    &lt;button (click)=&quot;toggleState()&quot;&gt;{{ yourVariableName === true ? &quot;ON&quot; : &quot;OFF&quot; }} /&gt;
&lt;/div&gt;

to this:

&lt;div class=&quot;toggle-button&quot;&gt;
    &lt;button (click)=&quot;toggleState()&quot;&gt;{{ yourVariableName === true ? &quot;ON&quot; : &quot;OFF&quot; }}&lt;/button&gt;
&lt;/div&gt;

You have messed up with the button start and end tag. Text "ON" and "OFF" should go between two button tags: &lt;button&gt;&lt;/button&gt;

huangapple
  • 本文由 发表于 2023年3月7日 11:11:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75657709.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定