div 标签的innerHTML 属性只能解析和渲染常规的HTML 元素,如输入等。要动态创建像mat-checkbox 这样的Angular 组件,您需要通知Angular 这些组件。让我们看看如何在下面做到这一点:
我们需要在 AppComponent 模板中有一个占位符,我们可以在其中动态添加 mat-checkbox 组件。在这种情况下,我们可以使用<ng-template> 标签作为占位符。
app.component.html
<mat-checkbox>mat-checkbox (static)</mat-checkbox> <hr />
dynamic angular component:<br/>
<ng-template #placeholder></ng-template>
在 AppComponent typescript 文件中,我们需要引用这个占位符并附加 mat-checkbox 组件。查找内联 cmets 进行说明。
app.component.ts
import {
Component,
ComponentFactoryResolver,
OnInit,
Renderer2,
ViewChild,
ViewContainerRef
} from '@angular/core';
import {MatCheckbox} from '@angular/material';
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
// Get reference to the ng-template placeholder tag
@ViewChild('placeholder', {read: ViewContainerRef, static: true}) placeholder: ViewContainerRef;
constructor(
private resolver: ComponentFactoryResolver,
private renderer: Renderer2) {}
ngOnInit() {
this.createComponent();
}
createComponent() {
// creating the mat-checkbox tag body content
let content = this.renderer.createText(' mat-checkbox (dynamic)');
// clear any previously appended element or component
this.placeholder.clear();
// resolve the MatCheckbox component and get the factory class to create the component dynamically
let factory = this.resolver.resolveComponentFactory(MatCheckbox);
// create the component and append to the placeholder in the template
let ref = this.placeholder.createComponent(factory);
// set the mat-checkbox body content
(ref.location.nativeElement as HTMLElement).appendChild(content);
}
}
为了使上述代码能够正常工作,我们需要通知 Angular 我们希望在运行时解析 MatCheckbox 组件。在 app.module.ts 中进行以下更改。
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { MatCheckboxModule, MatCheckbox } from '@angular/material';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
@NgModule({
imports: [ BrowserModule, FormsModule, MatCheckboxModule ],
declarations: [ AppComponent, HelloComponent ],
// Inform Angular about those components which will be created dynamically by including them in entryComponents field
entryComponents: [ MatCheckbox ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
现在您应该能够看到在运行时动态创建的 mat-checkbox。
在此处查看完整示例 (https://stackblitz.com/edit/angular-e7vhue)
有关详细信息,请参阅此article。
希望这对您的查询有所帮助。