我想在现有应用程序中应用html组件。
CreateMap<EmployeeDTO, Employee>().ForMember(dest => dest.CreatedDateTime, opts => opts.Ignore()).ForMember(dest => dest.UpdatedDateTime, opts => opts.Ignore());
它写入屏幕@Component({
selector: 'my-app',
template: `<ng-container> {{html}} </ng-container>`
})
export class AppComponent {
html = '<my-app></my-app>';
}
@Component({
selector: 'my',
template: `<span>{{name}}</span>`
})
export class MyComponent {
name = 'test';
}
,但它应该是"<my-app></my-app>"
答案 0 :(得分:0)
它将无法与Angular一起使用。也许如果您使用角度元素。
您需要做的第一件事是在某些元素上使用[innerHtml]
绑定来绑定html。您还需要将html标记为受信任的https://angular.io/api/platform-browser/DomSanitizer。完成此操作后,会将my-app
元素添加到DOM,但这不是角度组件。如果使用角度元素,它将变成一个组件。缺点是,与动态创建的组件(通过html)进行的所有交互都需要通过dom元素进行。好处是,现在您可以在任何地方创建角度组件,包括jQuery,角度Js或其他任何东西。
import { Component, Input } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
selector: 'custom-hello',
template: `
<h1>Hello {{name}}!</h1>
<div [innerHtml]="test"></div>
`,
styles: []
})
export class CustomHelloComponent {
@Input() name: string;
constructor(
private sanitizer: DomSanitizer,
) {
}
test = this.sanitizer.bypassSecurityTrustHtml('<my-test-component name="dynamic"></my-test-component>');
}
@Component({
selector: 'my-test-component',
template: `<h1>Hello {{name}}!</h1>`,
styles: []
})
export class MyTestComponent {
@Input() name: string;
}
下面显示了动态组件的倾斜方式,如此处记录的https://angular.io/guide/dynamic-component-loader所示,但是您需要组件引用,而不是选择器(并且组件需要位于模块的entryComponentes
中) :
https://stackblitz.com/edit/ng-dyn-component?file=src/app/app.component.ts
@Directive({
selector: '[container-ref]',
})
export class ContainerRefDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
@Component({
selector: 'my-app',
template: `<ng-template container-ref></ng-template>`
})
export class AppComponent {
@ViewChild(ContainerRefDirective, { static: true })
container: ContainerRefDirective;
constructor(private cfr: ComponentFactoryResolver) {
}
ngOnInit() {
const componentFactory = this.cfr.resolveComponentFactory(MyComponent);
const viewContainerRef = this.container.viewContainerRef;
const componentRef = viewContainerRef.createComponent(componentFactory);
}
}
@Component({
selector: 'my',
template: `<span>{{name}}</span>`
})
export class MyComponent {
name = 'test';
}