Hi Team
I have this code that creates a switch toggle button on and off, but when i try to create a function to call this property within a class. Its complaining its expecting a constructor or method. How do i fix this error "unexpected token"...?
According from the online IDE i am expected to work only on this page this is no Angular CLI project from local IDE.
`// code in Angular js 13
import { Component} from '@angular/core';
@Component({
selector: 'toggle-button',
template: `
`})
export class ToggleButton {
buttonState: boolean = false;
function toggleState() { // unexected token has an error
this.buttonState != this.buttonState;
}
}`
Naimish MakwanaPosted Mar 7, 2023, 5:42 AM
make sure that you have correctly added the
ToggleButtoncomponent to the template of another component that will render it.For example, if you want to render the toggle button component in the
app.component.htmltemplate, you can add the following code:If above added then it should work.
Thanks
Naimish Makwana
Guest UserPosted Mar 7, 2023, 5:28 AM
Hi Naimish
Thanks i did remove the function, the code compiles fine but now the UI is not showing. How can i fix that issue see here from the screen shot. I must be able to switch the button on and off, now its not showing but no errrors.
Naimish MakwanaPosted Mar 7, 2023, 5:18 AM
Hello Gcobani,
Firstly, you need to remove the
functionkeyword before thetoggleState()method since it's not needed in TypeScript.Secondly, you're using the wrong operator to toggle the
buttonStatevalue. Instead of!=, you should use the!operator to negate the current value.Try below code:
Thanks
Naimish Makwana