如何使用 Angular2 的属性指令添加一些 html 元素

use*_*105 7 angular2-directives angular

如果某个attribute directiveHMTL 元素上存在某个元素,我想显示一些额外的 html 内容。我已经搜索过,但找不到我要找的东西。例如,如果 P 标签有一个名为 的指令can-delete,那么我希望显示删除按钮。

<p can-delete>Hello World!</p>

这是我到目前为止得到的:

// >>> home.ts
import { Component } from "@angular/core";
import {canDelete } from "./can-delete.directive.ts";
@Component({
  templateUrl:"home.html",
  directives: [canDelete]
})
export class HomePage {

  constructor() {   }

}

// >>> home.html
<ion-header>
  <ion-navbar primary>
    <ion-title>
      Ionic 2
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
  Content...
  <p can-delete>Hello World!</p>
</ion-content>

// >>> can-delete.directive.ts
import { Directive, ElementRef } from "@angular/core";

@Directive({
  selector: "[can-delete]"
})
export class canDelete {
  constructor(el: ElementRef) {
   //show delete button
   //<button>Delete</button>
  }
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*srk 5

您的代码无效,所以这里有一个更新:

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appLoading]'
})
export class LoadingDirective {

  constructor(private elementRef:ElementRef){
    this.elementRef.nativeElement.innerHTML ='<h1>Hello World2</h1>';
  }
}
Run Code Online (Sandbox Code Playgroud)


Par*_*shi 0

为什么不使用 *ngIf。它可用于显示条件 HTML。

网页文件

<p>Hello World! <button type="button" *ngIf="showButton">Delete</button></p>

<button type="button" (click)="toggleButton()">Toggle</button>
Run Code Online (Sandbox Code Playgroud)

应用程序组件.ts

export class AppComponent implements OnInit{

    showButton:boolean;

constructor(){}

ngOnInit(){
    this.showButton = true;
}

toggleButton(){
   this.showButton = !this.showButton;
}

}
Run Code Online (Sandbox Code Playgroud)