我在strokeText.js周围做了一个指令包装,通过canvas api为文本添加一个笔画(或“大纲”)。在某些情况下,我正在抚摸动态文本,它会根据用户输入而改变。所以我这样设置:
<h2 strokeText [textContent]="totalPoints"></h2>
我的指令实现OnChanges
来响应绑定输入totalPoints
的更改,以便它可以重新描述文本:
import { Directive, ElementRef, Input, AfterViewInit, OnChanges } from '@angular/core';
import * as StrokeText from 'stroketext.js';
@Directive({
selector: '[strokeText]'
})
export class StrokeTextDirective implements AfterViewInit, OnChanges {
stroked: any;
@Input('strokeText') params: Array<any>;
@Input() textContent: string;
constructor(private el: ElementRef) { }
ngAfterViewInit() {
this.createStrokeText();
}
ngOnChanges(changes) {
console.log('changes', changes);
this.createStrokeText();
}
private createStrokeText() {
const thick = this.params[0] ? parseFloat(this.params[0]) : 3;
const color = this.params[1] ? this.params[1] : 'white';
if (this.stroked) { this.stroked.reset(); }
this.stroked = new StrokeText(this.el.nativeElement);
this.stroked.stroke(thick, color);
}
}
然而,这立即抛出Cannot read property 'name' of undefined, at checkBindingNoChanges (core.js:9912)
。即使我注释掉所有的strokeText内容,我仍然会收到错误。 (Angular v5.2.0)
StrokeText.js没有name属性,也没有此指令。我之前使用Angular时遇到了这个错误,当处理绑定属性时,它似乎是一个Angular错误。
我不知道它是否不喜欢我重复使用内置的textContent
指令,或者是否有其他错误。最终结果是,即使设置了totalPoints
,它也不会在h2中显示任何文本。我知道,因为我能做到
<h2 strokeText>{{ totalPoints }}</h2>
并且它工作正常,它只是不会对更改做出反应,并且笔划不会更新。
更新:简单地删除Input属性textContent也修复了错误,但它再次无法对更改做出反应。
Angular不允许您重复使用内置的Angular指令作为您自己的指令的属性。
您必须将相同的属性传递给不同名称的属性,如下所示:
<h1 strokeText [textToStroke]="totalPoints" [textContent]="totalPoints"></h1>
然后你可以像我在我的问题中那样使用ngOnChanges
来对变化做出反应。演示:
https://plnkr.co/edit/wJM9InkTxdDn3GIVS4yy?p=preview
注意,将Angular从5.2.0升级到5.2.4会使错误消失,并且在尝试将内置指令重用为我自己的指令的属性时,不会呈现该指令。