gpt4 book ai didi

angular - 添加 span 元素以显示错误消息

转载 作者:搜寻专家 更新时间:2023-10-30 21:34:23 25 4
gpt4 key购买 nike

我在字段上使用指令来阻止用户输入 html 标记以及 javascript 事件,但我遇到了几个问题:

a) 我希望能够在用户输入 html 标签或 javascript< 时立即显示错误消息/strong> 事件。

b) 我不想提醒错误消息,而是想在 span 标签显示错误消息(可能添加一个元素) .

谁能指出我正确的方向?非常感谢!

这是我的工作代码:

LIVE DEMO

@HostListener('keyup',['$event'])
onkeyup(event:any){

if (this.control.control.value.match(/<script.*?>.+<\/script>/i)) {
alert('HTML script tags are not allowed.');
}
else if(this.control.control.value.match(/<\/?\w+ +[^>]*on[a-z]+=["'].+["'][^>]*>/gi)){
alert('HTML event handlers are not allowed.');
}
}

最佳答案

您需要为额外的跨度添加自定义组件。添加 dom 元素需要在良好的 Angular 实践中使用结构指令:*directive

此结构指令不直接引用您应用它的元素,而是作为包装器工作,因此您需要使用 native 元素来获取对下一个兄弟元素的引用。

传递组件是否应该显示是通过组件实例完成的,但是 Angular 建议动态组件应该只通过服务进行通信,您可以这样做。但是对您的实时示例的更改有效:https://stackblitz.com/edit/primeng-dropdown-automation-84vitx

当然,您应该在 .module 中声明组件,并将自定义错误组件声明为入口组件,以便动态加载它们。

@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;

}
}

关于angular - 添加 span 元素以显示错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54031505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com