在Angular 14-15中,使用Angular Materials在动态创建的独立组件中可能会出现问题。最好的解决方法是确保在“NgModule”中将“CommonModule”和“MatButtonModule”导入到需要使用Angular Materials的组件中。
在下面的示例代码中,我们可以看到如何导入这些模块,并在独立组件中使用Button。组件的样式和生成在DOM中的方式不会对这个问题的解决方法产生影响。
app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { MyDynamicComponent } from './my-dynamic.component';
import { MatButtonModule } from '@angular/material/button';
import { CommonModule } from '@angular/common';
@NgModule({
imports: [BrowserModule, CommonModule, MatButtonModule],
declarations: [AppComponent, MyDynamicComponent],
bootstrap: [AppComponent],
entryComponents: [MyDynamicComponent],
})
export class AppModule { }
app.component.ts:
import { Component } from '@angular/core';
import { MyDynamicComponent } from './my-dynamic.component';
import { ViewContainerRef, ViewChild, AfterViewInit, ComponentFactoryResolver } from '@angular/core';
@Component({
selector: 'my-app',
template: `
`,
})
export class AppComponent implements AfterViewInit {
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver) { }
ngAfterViewInit() {
this.createComponent();
}
createComponent() {
this.container.clear();
const factory = this.resolver.resolveComponentFactory(MyDynamicComponent);
const componentRef = this.container.createComponent(factory);
}
}
my-dynamic.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'my-dynamic-component',
template: '',
})
上一篇:AngularMaterialStepper在Angular表单中与Mat-Grid-List不正确工作
下一篇:AngularMaterialTable和Paginator出现TypeError:无法读取未定义属性(读取'length')