您需要为额外的跨度添加自定义组件。添加DOM元素需要在良好的角度实践中使用结构指令:*指令
这个结构指令不直接引用应用它的元素,而是作为包装器工作,因此需要使用本机元素来获取对下一个同级的引用。
不管组件是否应该显示,传递都是通过组件实例完成的,不过角型的建议动态组件应该只通过服务进行通信,您可以这样做。但对您的现场示例的更改是有效的:
https://stackblitz.com/edit/primeng-dropdown-automation-84vitx
当然,您应该在.module中声明组件,并将自定义错误组件声明为条目组件,以便可以加载dynamicaly。
@Component({template:`<span *ngIf="show">No script tags please</span>`})
export class NoScriptComponent{
public show = false;
};
@Component({template:`<span *ngIf="show">No html tags please</span>`})
export class NoHtmlComponent{
public show = false;
};
@Directive({
selector: '[customTextField]'
})
export class CustomDropDownDirective {
const htmlError;
const jsError;
@Output() updateProperty: EventEmitter<any> = new EventEmitter();
constructor(private el: ElementRef, private template: TemplateRef<any>, private cfr: ComponentFactoryResolver, private vcr: ViewContainerRef) {
}
ngOnInit() {
this.vcr.createEmbeddedView(this.template)
const next = this.template.elementRef.nativeElement.nextElementSibling;
next.onkeyup = this.onkeyup.bind(this);
const cmpJsFactory = this.cfr.resolveComponentFactory(NoScriptComponent);
this.jsError = this.vcr.createComponent(cmpJsFactory)
const cmpHtmlFactory = this.cfr.resolveComponentFactory(NoHtmlComponent);
this.htmlError = this.vcr.createComponent(cmpHtmlFactory)
}
onkeyup(event:any){
const value = event.target.value;
if (value.match(/<script.*?>.+<\/script>/i)) {
this.jsError.instance.show=true;
}
else if(value.match(/<\/?\w+ +[^>]*on[a-z]+=["'].+["'][^>]*>/gi)){
this.htmlError.instance.show=true;
} else {
this.jsError.instance.show= false;
this.htmlError.instance.show= false;
}
}