简体   繁体   中英

Angular toggle button to add text to p tag

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);  
         }}

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
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM