Angular 2 hide and show element using *ngIf with boolean

前端 未结 1 1996
青春惊慌失措
青春惊慌失措 2021-01-13 14:45

I want to show and hide an element by using a button that\'s located in another component.

So I have a Dashboard with an amount of chambers in it and a header.

1条回答
  •  孤城傲影
    2021-01-13 15:26

    Plunker

    There was a small mismatch between the @Input() kamers and the template *ngIf="kamer.patient == null".

    • Just change the input to kamer.

    Template HTML

    
       

    {{kamer.id}}

    Component

    @Component({
      selector: 'material-app',
      templateUrl: 'app.component.html'
    })
    export class AppComponent {
    
      kamer = {
        patient: null,
        id: '1'
      };
      showId = false;
    
      ngOnInit() {
    
      }
    
      toggleId() {
        this.showId = !this.showId;
      }
    
    }
    

    Update (1) - Plunker (1)

    Use @ViewChild

    To reference a child component's functions use ViewChild

    • Place @ViewChild('child') child; in the parent component
    • In the parent template reference child functions like this:

    Parent Component

    @Component({
      selector: 'material-app',
      template: `
        
        
      `
    })
    export class AppComponent {
    
      @ViewChild('child') child;
    
    }
    

    Child Template

    
       

    {{kamer.id}}

    Child Component

    @Component({
      selector: 'material-child',
      templateUrl: 'app.component.html'
    })
    export class ChildComponent {
    
      kamer = {
        patient: null,
        id: '1'
      };
      showId = false;
    
      ngOnInit() {
    
      }
    
      toggleId() {
        this.showId = !this.showId;
      }
    
    }
    

    Update (2) - Plunker (2)

    Use @Output() + EventEmitter

    To extend the previous setup to use a sibling component you can

    • Have the sibling emit an event using an EventEmitter
    • Listen to the emitted event in the parent component, and call the child function needed using ViewChild

    Sibling Component

    @Component({
      selector: 'material-sibling',
      template: `
        
      `
    })
    export class SiblingComponent {
      @Output() toggle = new EventEmitter();
    }
    

    Parent Component

    @Component({
      selector: 'material-app',
      template: `
        
        
      `
    })
    export class AppComponent {
    
      @ViewChild('child') child;
    
    }
    

    Child Template

    
       

    {{kamer.id}}

    Child Component

    @Component({
      selector: 'material-child',
      templateUrl: 'app.component.html'
    })
    export class ChildComponent {
    
      kamer = {
        patient: null,
        id: '1'
      };
      showId = false;
    
      ngOnInit() {
    
      }
    
      toggleId() {
        this.showId = !this.showId;
      }
    
    }
    

    0 讨论(0)
提交回复
热议问题