Angular 4 替换 DOM 元素



我有一个关于 DOM 替换为角度的问题。 当我点击我的按钮时,我通过了$event。 我的目标是用另一个带有文本的div 替换按钮子项。

你能帮我吗?

<button 
type="button" 
class="btn LG_btn-grey animated" 
(click)="onSubmitResendEmail(user.email, $event);sharedService.getCurrentURL()">
<app-icons-renderer 
[name]="'sendEmail'">
</app-icons-renderer>
</button>

您可以为button提供一个模板变量。然后在您的类中,使用@ViewChild访问它。然后使用Renderer2向其添加子项。

下面是一个按钮示例,该按钮使用它在其中添加新内容。

组件类

import { Component, ViewChild, Renderer2, ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
@ViewChild('myButton') myButton: ElementRef;
constructor(private renderer: Renderer2) {}
clickHandler() {
const div = this.renderer.createElement('div');
const text = this.renderer.createText('Some text in div');
this.renderer.appendChild(div, text);
this.renderer.appendChild(this.myButton.nativeElement, div);
}
}

模板

<button 
#myButton
type="button" 
class="btn LG_btn-grey animated" 
(click)="clickHandler()">
<p>Some content</p>
</button>

另类:

如果您有一些字符串形式的 HTML,要将其设置为按钮的内容,

import { Component, ViewChild, Renderer2, ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
@ViewChild('myButton') myButton: ElementRef;
constructor(
private renderer: Renderer2
) {}
newContent = `<div>Some text in div</div>`;
clickHandler() {
this.renderer.setProperty(this.myButton.nativeElement, 'innerHTML', this.newContent);
}
}

示例堆栈闪电战。

为什么没有标志值来告诉你哪个元素是可见的, 像这样:

<button>
<app-icons-renderer [style.visibility]="isEmailSent ? 'hidden' : 'visible'" [name]="'sendEmail'">
</app-icons-renderer>
<app-icons-renderer [style.visibility]="isEmailSent ? 'visible' : 'hidden'" [name]="'sentEmail'">
</app-icons-renderer>
</button>

您可以使用按钮单击事件更改isEmailSenting值。

更新: 不确定这是否会占用空间,更好的选择可能是使用

<app-icons-renderer *ngIf="isEmailSent"
<app-icons-renderer *ngIf="!isEmailSent"

最新更新