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

标签 angular typescript primeng

我在字段上使用指令来阻止用户输入 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/

相关文章:

javascript - 如果 @Input 是一个对象及其属性更新之一,则 OnChanges 不会触发

html - 在 Angular 中转换 CSS 类?

javascript - 方法如何将 null 作为接口(interface)返回

typescript - 强制 Protobuf.js 忽略无法识别的 JS 端字段

typescript - FP-TS 分支(面向铁路的编程)

json - 如何使用 angular2 react 形式构建嵌套数组?

Angular 6,构建无法在 Firebase 托管上加载图像

Angular PrimeNG p 表 : add custom sorting function to specific column

angular - 使用按键选择 PrimeNG 表上的行

javascript - 当放大浏览器导致一个 div 容器扩展时,如何调整其他 div 容器的长度以保持在同一底线?