如果你在Angular 12中遇到了这个错误:Can't bind to 'scrollIntoForm' since it isn't a known property of 'form', 下面的代码分享可以帮助你解决该问题。
我们可以通过使用@Input()装饰器为指令添加一个输入属性scrollIntoForm,这样,我们就可以在模板中将该属性绑定到我们所需要的值。
以下是一个示例:
@Directive({ selector: '[scrollInto]', }) export class ScrollIntoViewDirective { @Input() scrollInto: string;
constructor(private el: ElementRef) { }
ngOnChanges() { if (this.scrollInto) { this.el.nativeElement.scrollIntoView(true); } } }
在上面的代码中,我们使用了@Input()装饰器将scrollInto属性添加到ScrollIntoViewDirective指令中。在ngOnChanges中使用了传递给指令的值来调用el.nativeElement.scrollIntoView(true)方法。
现在我们可以在模板中使用 scrollIntoForm 属性来绑定我们的指令了。
例如,你可以在@NgModule装饰器中将指令添加到指令列表中:
@NgModule({ declarations: [ScrollIntoViewDirective], exports: [ScrollIntoViewDirective] }) export class AppModule {}
在模板中使用指令: