【问题标题】:Custom Angular Compiler Errors自定义 Angular 编译器错误
【发布时间】:2021-11-25 22:23:55
【问题描述】:

我很好奇是否有任何方法可以在控制台中添加自定义警告,类似于当您尝试在已经绑定到 FormControl 的输入上使用“禁用”属性时 Angular 抛出的警告.ts 文件。基本上,Angular 建议您在 .ts 磁贴中修改 FormControl 本身的“禁用”属性,而不是在模板中指定 HTML 属性。

为了确保 FormControl 的“状态”操作代码完全在 .ts 文件中完成,每当有人尝试在 HTML 模板中使用所说的“必需”属性时,我还想在控制台中发出类似的警告而不是直接将 Validators.required 验证器添加到 FormControl。

什么是实现这种警告的好方法?

【问题讨论】:

    标签: angular


    【解决方案1】:

    reactive_errors.ts

    static disabledAttrWarning(): void {
        console.warn(`
          It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true
          when you set up this control in your component class, the disabled attribute will actually be set in the DOM for
          you. We recommend using this approach to avoid 'changed after checked' errors.
    
          Example:
          form = new FormGroup({
            first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
            last: new FormControl('Drew', Validators.required)
          });
        `);
      }
    

    所以基本上 - 这只是一个写得很好的console.warn。 为了对required 属性做类似的事情,您可以使用[required] 选择器检测带有指令的元素 - 并在其ngAfterViewInit() 上添加console.warn

    【讨论】:

    • 很好的建议,谢谢!
    【解决方案2】:

    正如其他答案中提到的,您可以为此创建一个指令。您可能想要处理具有 formcontrol 或 formcontrolname 的字段,这里是 formControlName

    @Directive({
      selector: 'input[formControlName]'
    })
    export class RequiredDirective {
    
      constructor(private el: ElementRef) { 
        if (this.el.nativeElement.required) {
          console.error("set the required attribute on the formcontrol")
        }
      }
    }
    

    演示:https://stackblitz.com/edit/angular-gfbvbg?file=src%2Fapp%2Frequired.directive.ts

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-18
      • 2016-04-02
      • 2019-02-19
      • 2017-05-03
      相关资源
      最近更新 更多