Search code examples
angularangularjstypescriptformscomponents

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


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 '@angular/core';

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

export class ToggleButton {
    buttonState: boolean = false;

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


  [1]: https://i.sstatic.net/0sgd8.png

Solution

  • Modify your template from this:

    <div class="toggle-button">
        <button (click)="toggleState()">{{ yourVariableName === true ? "ON" : "OFF" }} />
    </div>
    

    to this:

    <div class="toggle-button">
        <button (click)="toggleState()">{{ yourVariableName === true ? "ON" : "OFF" }}</button>
    </div>
    

    You have messed up with the button start and end tag. Text "ON" and "OFF" should go between two button tags: <button></button>