我有一个html文件,其中包含一些有角度的材料。在按钮上我想将此内容添加到我的表单中。那可能吗? 问题是我在角度渲染材料之前只添加了我需要的原始html。
txt.html:
<mat-card-actions>
<button mat-button>LIKE</button>
<button mat-button>SHARE</button>
</mat-card-actions>
form.componant.ts
@ViewChild('one') d1: ElementRef;
txt = require('./txt.html');
public add(){
this.d1.nativeElement.insertAdjacentHTML('beforeend', this.txt);
}
form.componant.html:
<form>
<section #one></section>
</form>
我想我必须再次编译页面。我用ng-change尝试了它:
<body ng-controller="MainCtrl" ng-model="demo" ng-change="comp();">
我找到了一个基于本教程的解决方案: https://angular.io/guide/dynamic-component-loader
答案 0 :(得分:0)
您是否希望动态注入此内容,而不仅仅是隐藏?您可以轻松设置show变量:
<mat-card-actions *ngIf="showLikeShareButtons">
<button mat-button>LIKE</button>
<button mat-button>SHARE</button>
</mat-card-actions>
然后在你的组件内:
export class ..... {
public showLikeShareButtons = false;
public add() { this.showLikeShareButtons = true; }
答案 1 :(得分:0)
要将dom添加到现有表单,可以将内容绑定到DIV。请参阅以下代码段:
form.componant.html:
<form>
<section #one>
<div [innerHtml]="txt | keepHtml: 'html'"></div>
</section>
</form>
创建一个新的管道safe.ts:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
@Pipe({ name: 'keepHtml', pure: false })
export class SafePipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) {
}
public transform(value: string, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
switch (type) {
case 'html':
return this._sanitizer.bypassSecurityTrustHtml(value);
case 'style':
return this._sanitizer.bypassSecurityTrustStyle(value);
case 'script':
return this._sanitizer.bypassSecurityTrustScript(value);
case 'url':
return this._sanitizer.bypassSecurityTrustUrl(value);
case 'resourceUrl':
return this._sanitizer.bypassSecurityTrustResourceUrl(value);
default:
throw new Error(`Unable to bypass security for invalid type: ${type}`);
}
}
}
注意:不要忘记将管道添加到您的应用模块。
form.componant.ts
@ViewChild('one') d1: ElementRef;
public add(){
txt = require('./txt.html');
}