Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

angular - How to make a formControl readonly

How to make a formControl in angular readonly

I know i can do it in html like

<input type="text" formControlName="xyz" readonly />

how to do it from JS Code and not html i.e in a model driven way

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are using Reactive Forms you can assign it dynamically like in the example code below (email field)

    this.registerForm = this.formBuilder.group({
          first_name: ['', Validators.required],
          last_name: ['', Validators.required],
          email: new FormControl({value: null, disabled: true}, Validators.required),
          password: ['', Validators.compose([Validators.required, Validators.email])],
          confirm_password: ['', Validators.required],
    });

If you want to get all the values including disabled controls you should use:

    this.registerForm.getRawValue();

View method comment on source code

    /**
       * The aggregate value of the `FormGroup`, including any disabled controls.
       *
       * If you'd like to include all values regardless of disabled status, use this method.
       * Otherwise, the `value` property is the best way to get the value of the group.
       */
      getRawValue(): any;

Enjoy coding!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...