如何在angular2中动态删除和添加组件?

时间:2016-10-20 20:51:21

标签: angular

我定义了一个组件" FancyButton"。我在模板中有这个:

...
<div class="container">
  <div class="fancy">
    <fancybutton></fancybutton>
  </div>
  <button (click)="removeFancyButton">Remove</button>
  <button (click)="addFancyButton">Add</button>
</div>
...

我的问题是,我如何以编程方式删除:

  <div class="fancy">
    <fancybutton></fancybutton>
  </div>

当我点击删除按钮?相反,我该如何重新添加?如果可能的话,我希望它能触发ngOnDestroy,如果它重新添加&#34;,则在重新添加时触发ngOnInit。

这是我的花哨按钮组件,下面是我在home.component.html中集成了花式按钮的父模板:

@Component({
  selector: 'fancy-button',
  template: `<button>clickme</button>`
})
export class FancyButton {}

@Component({
  selector: 'home',  // <home></home>
  providers: [
    Title
  ],
  styleUrls: [ './home.component.css' ],
  templateUrl: './home.component.html'
})

4 个答案:

答案 0 :(得分:6)

尝试*ngIf,当它不应该被显示时它会移除dom元素,并且当它是

时相反地添加dom元素
  

基于{expression}删除或重新创建DOM树的一部分。

...
<div class="container">
  <div *ngIf="showButton" class="fancy">
    <fancybutton></fancybutton>
  </div>
  <button (click)="removeFancyButton">Remove</button>
  <button (click)="addFancyButton">Add</button>
</div>
...

@Component({
  selector: 'home',  // <home></home>
  providers: [
    Title
  ],
  styleUrls: [ './home.component.css' ],
  templateUrl: './home.component.html',
  directives: [FancyButton],
})
export class Home {
    showButton: Boolean = true;

    addFancyButton() {
        // Do everything you need to
        this.showButton = true;
    }
    removeFancyButton() {
        // Do everything you need to
        this.showButton = false;
    }
}

答案 1 :(得分:0)

声明一些组件属性,如isFancyBtnVisible = true,并在点击时更改它。然后使用* ngIf =&#34; isFancyBtnVisible&#34;在您的按钮组件上

答案 2 :(得分:0)

如果使用* ngIf,它将在true时调用ngOnOnit,在false时调用ngOnDestroy。

<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"> <wsu:Timestamp> <wsu:Created>2016-02-19T16:36:21Z</wsu:Created> <wsu:Expires>2016-02-19T16:41:21Z</wsu:Expires> </wsu:Timestamp> <wsse:UsernameToken> <wsse:Username>username</wsse:Username> <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">password</wsse:Password> <wsu:Created>2016-02-19T16:36:21Z</wsu:Created> </wsse:UsernameToken> </wsse:Security>

答案 3 :(得分:0)

您只能强制删除必须添加的组件。有关示例,请参阅Angular 2 dynamic tabs with user-click chosen components。否则使用*ngIf="expr"。如果表达式为false,则删除内容。