I am trying to create a structural directive within a mat-form-field (Angular Material). The goal is to have a an icon that can clear the input field’s content.
I am dynamically creating a component within the structural directive. Unfortuntely, I get an Error “mat-form-field must contain a MatFormFieldControl”
Questions:
- What am I doing wrong that is causing this error to occur?
- How can I adjust my directive to fix this issue?
Thank you in advance for your help!
Currently, I have the following code:
HTML:
<mat-form-field>
<input matInput *appClearable>
</mat-form-field>
Directive:
@Directive({
selector: '[appClearable]',
standalone: true
})
export class ClearableDirective implements OnInit, DoCheck {
private viewContainerRef = inject(ViewContainerRef);
private templateRef = inject(TemplateRef);
private templateView?: EmbeddedViewRef<any>;
ngOnInit(): void {
this.templateView = this.templateRef.createEmbeddedView({});
this.viewContainerRef.createComponent(ClearableComponent, {
injector: this.viewContainerRef.injector,
projectableNodes: [this.templateView.rootNodes]
});
}
ngDoCheck(): void {
if (this.templateView) {
this.templateView.detectChanges();
}
}
}
Component:
@Component({
selector: 'app-clearable',
standalone: true,
imports: [
MatIcon,
MatIconButton,
MatSuffix
],
template: `
<ng-content></ng-content>
<button mat-icon-button type="button" matSuffix>
<mat-icon>close</mat-icon>
</button>`
})
class ClearableComponent {}