Conditionally make input field readonly in Angular 2 or 4: Advice + Best/which way to do it

后端 未结 4 1554
伪装坚强ぢ
伪装坚强ぢ 2021-02-05 00:34

I was attempting to answer someone elses question. And in doing so realised there was quite a bit of uncertainty in my mind about a few things. I\'m hoping someone can provide f

4条回答
  •  孤独总比滥情好
    2021-02-05 01:19

    None of them worked for me.. Finally found solution by creating custom directive angular.. Directives are powerful feature of angular

    1. Create Custom Directive

    @Directive({
      selector: '[readonly],[readOnly]',
      host: {
        '[attr.readonly]': '_isReadonly ? "" : null'
      }
    })
    class ReadonlyDirective {
      _isReadonly = false;
    
      @Input() set readonly (v) {
         this._isReadonly = coerceBooleanProperty(v);
      };
    
      ngOnChanges(changes) {
        console.log(changes);
      }
    }

    1. Add into module declarations

    @NgModule({
      ...
      declarations: [ ..., ReadonlyDirective ],
      ...
    })
    3. Now its time to use directive as following.

    
    or
    
    Directives are powerful feature of angular, I strongly recommend you to go through https://angular.io/guide/attribute-directives

    Demo https://stackblitz.com/edit/angular-readonly-input-aifncy?file=src/app/app.component.ts

提交回复
热议问题