I have a toggle button , which when clicked should add text 'Dark' to the
tag. When clicked again should replace with 'Light'. Initially there shouldn't be anything.Suppose to use `
@Component({
selector: 'darkmode-toggler',
template: `<div>
<button>Toggle dark mode</button>
<p></p>
</div>`,
styles: []
})
export class DarkModeToggler { }
@Component({
selector: 'app-root',
template: `<div>
<darkmode-toggler (stateChanged)="handleStateChange($event)">
</darkmode-toggler>
</div>`,
styles: []
})
export class Resource {
handleStateChange(event) {
console.log(event);
}}
CodePudding user response:
I'm not completely sure what you want (a better description would be great), but what I understand from your answer you could do something like this:
@Component({
selector: 'app-component',
template: `
<button (click)="toggleDarkMode()">Toggle dark mode</button>
<p>{{isDarkMode ? 'dark' : 'light'}} mode</p>
`
})
export class AppComponent {
public isDarkMode = false;
public toggleDarkMode(): void {
this.isDarkMode = !this.isDarkMode;
}
}
or:
type Theme = 'dark' | 'light';
@Component({
selector: 'app-component',
template: `
<button (click)="toggleDarkMode()">Toggle dark mode</button>
<p>{{theme}} mode</p>
`
})
export class AppComponent {
public theme: Theme = 'light';
public toggleDarkMode(): void {
this.theme = this.theme === 'light' ? 'dark' : 'light';
}
}
Edit
In the darkmode-toggler
component you can do what was mentioned above to change the paragraph's text.
And then use @Output
to give it a custom event.
If I edit your sample it would look like this:
@Component({
selector: 'darkmode-toggler',
template: `
<div>
<button>Toggle dark mode</button>
<p>{{isDarkMode ? 'dark' : 'light'}} mode</p>
</div>
`,
styles: []
})
export class DarkModeToggler {
@Output() stateChanged = new EventEmitter<boolean>();
isDarkMode = false;
public toggleDarkMode(): void {
this.isDarkMode = !this.isDarkMode;
this.stateChanged.emit(this.isDarkMode); // you emit a change here
}
}
@Component({
selector: 'app-root',
template: `
<div>
<darkmode-toggler (stateChanged)="handleStateChange($event)">
</darkmode-toggler>
</div>
`,
styles: []
})
export class Resource {
handleStateChange(event) {
console.log(event); // since I made a EventEmitter<boolean>() and I'm emitting the isDarkMode variable's value it'll be true or false
}
}