mat-form-field always show required red color?










-1















Is there any way to always show the red color of a mat-form-field when it have the required="true", even if I never set the focus on it or I touched it?



<mat-form-field color="accent">
<input matInput placeholder="ID is required" required="true [(ngModel)]="uniqueID">
</mat-form-field>


I just want to show the red color of the error but from the beginning, before I even touch the input.



How Is it posible?










share|improve this question
























  • share your html code

    – Sunil Singh
    Nov 15 '18 at 21:25











  • @SunilSingh I just update the question

    – Sergio Mendez
    Nov 15 '18 at 21:35











  • Initial observation. double quote missing after required true.

    – Shabbir Dhangot
    Nov 16 '18 at 4:18











  • You don't have to set the required attribute to true.

    – Edric
    Nov 16 '18 at 4:42











  • You could also use a custom ErrorStateMatcher: material.angular.io/components/input/…

    – Edric
    Nov 16 '18 at 4:45















-1















Is there any way to always show the red color of a mat-form-field when it have the required="true", even if I never set the focus on it or I touched it?



<mat-form-field color="accent">
<input matInput placeholder="ID is required" required="true [(ngModel)]="uniqueID">
</mat-form-field>


I just want to show the red color of the error but from the beginning, before I even touch the input.



How Is it posible?










share|improve this question
























  • share your html code

    – Sunil Singh
    Nov 15 '18 at 21:25











  • @SunilSingh I just update the question

    – Sergio Mendez
    Nov 15 '18 at 21:35











  • Initial observation. double quote missing after required true.

    – Shabbir Dhangot
    Nov 16 '18 at 4:18











  • You don't have to set the required attribute to true.

    – Edric
    Nov 16 '18 at 4:42











  • You could also use a custom ErrorStateMatcher: material.angular.io/components/input/…

    – Edric
    Nov 16 '18 at 4:45













-1












-1








-1








Is there any way to always show the red color of a mat-form-field when it have the required="true", even if I never set the focus on it or I touched it?



<mat-form-field color="accent">
<input matInput placeholder="ID is required" required="true [(ngModel)]="uniqueID">
</mat-form-field>


I just want to show the red color of the error but from the beginning, before I even touch the input.



How Is it posible?










share|improve this question
















Is there any way to always show the red color of a mat-form-field when it have the required="true", even if I never set the focus on it or I touched it?



<mat-form-field color="accent">
<input matInput placeholder="ID is required" required="true [(ngModel)]="uniqueID">
</mat-form-field>


I just want to show the red color of the error but from the beginning, before I even touch the input.



How Is it posible?







angular angular-material angular-material2






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 21:34







Sergio Mendez

















asked Nov 15 '18 at 21:20









Sergio MendezSergio Mendez

1641216




1641216












  • share your html code

    – Sunil Singh
    Nov 15 '18 at 21:25











  • @SunilSingh I just update the question

    – Sergio Mendez
    Nov 15 '18 at 21:35











  • Initial observation. double quote missing after required true.

    – Shabbir Dhangot
    Nov 16 '18 at 4:18











  • You don't have to set the required attribute to true.

    – Edric
    Nov 16 '18 at 4:42











  • You could also use a custom ErrorStateMatcher: material.angular.io/components/input/…

    – Edric
    Nov 16 '18 at 4:45

















  • share your html code

    – Sunil Singh
    Nov 15 '18 at 21:25











  • @SunilSingh I just update the question

    – Sergio Mendez
    Nov 15 '18 at 21:35











  • Initial observation. double quote missing after required true.

    – Shabbir Dhangot
    Nov 16 '18 at 4:18











  • You don't have to set the required attribute to true.

    – Edric
    Nov 16 '18 at 4:42











  • You could also use a custom ErrorStateMatcher: material.angular.io/components/input/…

    – Edric
    Nov 16 '18 at 4:45
















share your html code

– Sunil Singh
Nov 15 '18 at 21:25





share your html code

– Sunil Singh
Nov 15 '18 at 21:25













@SunilSingh I just update the question

– Sergio Mendez
Nov 15 '18 at 21:35





@SunilSingh I just update the question

– Sergio Mendez
Nov 15 '18 at 21:35













Initial observation. double quote missing after required true.

– Shabbir Dhangot
Nov 16 '18 at 4:18





Initial observation. double quote missing after required true.

– Shabbir Dhangot
Nov 16 '18 at 4:18













You don't have to set the required attribute to true.

– Edric
Nov 16 '18 at 4:42





You don't have to set the required attribute to true.

– Edric
Nov 16 '18 at 4:42













You could also use a custom ErrorStateMatcher: material.angular.io/components/input/…

– Edric
Nov 16 '18 at 4:45





You could also use a custom ErrorStateMatcher: material.angular.io/components/input/…

– Edric
Nov 16 '18 at 4:45












2 Answers
2






active

oldest

votes


















0














The following demo shows the required case in an existing angular material reactive form.



Application Demo :
https://stackblitz.com/edit/example-angular-material-reactive-form-2rksrw?file=app/app.component.ts



Approach :



  • In ngOnInit, we can get the input element from the form and can modify as
    this.formGroup.get('name').markAsTouched();

  • We can also exploit the touched property of the from input as
    this.formGroup.get('name').touched = true;, but this will generate an error Cannot assign to 'touched' because it is a constant or a read-only property.
    But in the stackblitz demo, you can see it working as we can see the difference with this.formGroup.get('name').touched = false; also.

The formGroup is created in following manner in the demo form :



 this.formGroup = this.formBuilder.group(
'email': [null, [Validators.required, Validators.pattern(emailregex)]],
'name': [null, Validators.required],
'password': [null, [Validators.required, this.checkPassword]],
'description': [null, [Validators.required]],
'validate': ''
);





share|improve this answer






























    0














    If you are willing to use reactive forms... using ngAfterViewInit, you could programmatically mark the field as touched to force the error.




    • Unfortunately I am not familiar with how to accomplish this via
      template driven forms.



      setTimeout(() => 
      this.yourForm.controls['yourControl'].markAsTouched();
      , 0);


    Revision



    Based on my original answer, and the expansion of my answer by Abhishek to re-enforce that you can do this with reactive forms... I wanted to provide the template driven form scenario as well.



    • The common theme here, regardless if you use reactive forms or template driven forms is that, you need to programmatically mark the
      input as touched...

    • In template driven forms you will also need to do
      the same via template reference so that you can call the markAsTouched() method on the control in
      your ngOnInit life cycle hook.

    Set a template reference of id and bind it to ngModel via #id="ngModel" on the input... you will also need to assign a name on the input of id via name="id" this is a requirement of binding to ngModel.



    <mat-form-field color="accent">
    <input matInput placeholder="ID is required" required="true" [(ngModel)]="uniqueID" name="id" #id="ngModel">
    </mat-form-field>

    <div *ngIf="id.invalid && (id.dirty || id.touched)">
    <mat-error *ngIf="id.errors.required">
    ID is <strong>required</strong>
    </mat-error>
    </div>

    <pre>id.errors: id.errors </pre>


    From here you will need to use @ViewChild in your component to get reference to #id and call markAsTouched() on the control via ngOnInit life cycle hook.



    import Component, OnInit, ViewChild from '@angular/core';

    @ViewChild('id') _id : any

    ngOnInit()
    this._id.control.markAsTouched();






    share|improve this answer
























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53328049%2fmat-form-field-always-show-required-red-color%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      The following demo shows the required case in an existing angular material reactive form.



      Application Demo :
      https://stackblitz.com/edit/example-angular-material-reactive-form-2rksrw?file=app/app.component.ts



      Approach :



      • In ngOnInit, we can get the input element from the form and can modify as
        this.formGroup.get('name').markAsTouched();

      • We can also exploit the touched property of the from input as
        this.formGroup.get('name').touched = true;, but this will generate an error Cannot assign to 'touched' because it is a constant or a read-only property.
        But in the stackblitz demo, you can see it working as we can see the difference with this.formGroup.get('name').touched = false; also.

      The formGroup is created in following manner in the demo form :



       this.formGroup = this.formBuilder.group(
      'email': [null, [Validators.required, Validators.pattern(emailregex)]],
      'name': [null, Validators.required],
      'password': [null, [Validators.required, this.checkPassword]],
      'description': [null, [Validators.required]],
      'validate': ''
      );





      share|improve this answer



























        0














        The following demo shows the required case in an existing angular material reactive form.



        Application Demo :
        https://stackblitz.com/edit/example-angular-material-reactive-form-2rksrw?file=app/app.component.ts



        Approach :



        • In ngOnInit, we can get the input element from the form and can modify as
          this.formGroup.get('name').markAsTouched();

        • We can also exploit the touched property of the from input as
          this.formGroup.get('name').touched = true;, but this will generate an error Cannot assign to 'touched' because it is a constant or a read-only property.
          But in the stackblitz demo, you can see it working as we can see the difference with this.formGroup.get('name').touched = false; also.

        The formGroup is created in following manner in the demo form :



         this.formGroup = this.formBuilder.group(
        'email': [null, [Validators.required, Validators.pattern(emailregex)]],
        'name': [null, Validators.required],
        'password': [null, [Validators.required, this.checkPassword]],
        'description': [null, [Validators.required]],
        'validate': ''
        );





        share|improve this answer

























          0












          0








          0







          The following demo shows the required case in an existing angular material reactive form.



          Application Demo :
          https://stackblitz.com/edit/example-angular-material-reactive-form-2rksrw?file=app/app.component.ts



          Approach :



          • In ngOnInit, we can get the input element from the form and can modify as
            this.formGroup.get('name').markAsTouched();

          • We can also exploit the touched property of the from input as
            this.formGroup.get('name').touched = true;, but this will generate an error Cannot assign to 'touched' because it is a constant or a read-only property.
            But in the stackblitz demo, you can see it working as we can see the difference with this.formGroup.get('name').touched = false; also.

          The formGroup is created in following manner in the demo form :



           this.formGroup = this.formBuilder.group(
          'email': [null, [Validators.required, Validators.pattern(emailregex)]],
          'name': [null, Validators.required],
          'password': [null, [Validators.required, this.checkPassword]],
          'description': [null, [Validators.required]],
          'validate': ''
          );





          share|improve this answer













          The following demo shows the required case in an existing angular material reactive form.



          Application Demo :
          https://stackblitz.com/edit/example-angular-material-reactive-form-2rksrw?file=app/app.component.ts



          Approach :



          • In ngOnInit, we can get the input element from the form and can modify as
            this.formGroup.get('name').markAsTouched();

          • We can also exploit the touched property of the from input as
            this.formGroup.get('name').touched = true;, but this will generate an error Cannot assign to 'touched' because it is a constant or a read-only property.
            But in the stackblitz demo, you can see it working as we can see the difference with this.formGroup.get('name').touched = false; also.

          The formGroup is created in following manner in the demo form :



           this.formGroup = this.formBuilder.group(
          'email': [null, [Validators.required, Validators.pattern(emailregex)]],
          'name': [null, Validators.required],
          'password': [null, [Validators.required, this.checkPassword]],
          'description': [null, [Validators.required]],
          'validate': ''
          );






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 16 '18 at 4:16









          Abhishek KumarAbhishek Kumar

          1,165416




          1,165416























              0














              If you are willing to use reactive forms... using ngAfterViewInit, you could programmatically mark the field as touched to force the error.




              • Unfortunately I am not familiar with how to accomplish this via
                template driven forms.



                setTimeout(() => 
                this.yourForm.controls['yourControl'].markAsTouched();
                , 0);


              Revision



              Based on my original answer, and the expansion of my answer by Abhishek to re-enforce that you can do this with reactive forms... I wanted to provide the template driven form scenario as well.



              • The common theme here, regardless if you use reactive forms or template driven forms is that, you need to programmatically mark the
                input as touched...

              • In template driven forms you will also need to do
                the same via template reference so that you can call the markAsTouched() method on the control in
                your ngOnInit life cycle hook.

              Set a template reference of id and bind it to ngModel via #id="ngModel" on the input... you will also need to assign a name on the input of id via name="id" this is a requirement of binding to ngModel.



              <mat-form-field color="accent">
              <input matInput placeholder="ID is required" required="true" [(ngModel)]="uniqueID" name="id" #id="ngModel">
              </mat-form-field>

              <div *ngIf="id.invalid && (id.dirty || id.touched)">
              <mat-error *ngIf="id.errors.required">
              ID is <strong>required</strong>
              </mat-error>
              </div>

              <pre>id.errors: id.errors </pre>


              From here you will need to use @ViewChild in your component to get reference to #id and call markAsTouched() on the control via ngOnInit life cycle hook.



              import Component, OnInit, ViewChild from '@angular/core';

              @ViewChild('id') _id : any

              ngOnInit()
              this._id.control.markAsTouched();






              share|improve this answer





























                0














                If you are willing to use reactive forms... using ngAfterViewInit, you could programmatically mark the field as touched to force the error.




                • Unfortunately I am not familiar with how to accomplish this via
                  template driven forms.



                  setTimeout(() => 
                  this.yourForm.controls['yourControl'].markAsTouched();
                  , 0);


                Revision



                Based on my original answer, and the expansion of my answer by Abhishek to re-enforce that you can do this with reactive forms... I wanted to provide the template driven form scenario as well.



                • The common theme here, regardless if you use reactive forms or template driven forms is that, you need to programmatically mark the
                  input as touched...

                • In template driven forms you will also need to do
                  the same via template reference so that you can call the markAsTouched() method on the control in
                  your ngOnInit life cycle hook.

                Set a template reference of id and bind it to ngModel via #id="ngModel" on the input... you will also need to assign a name on the input of id via name="id" this is a requirement of binding to ngModel.



                <mat-form-field color="accent">
                <input matInput placeholder="ID is required" required="true" [(ngModel)]="uniqueID" name="id" #id="ngModel">
                </mat-form-field>

                <div *ngIf="id.invalid && (id.dirty || id.touched)">
                <mat-error *ngIf="id.errors.required">
                ID is <strong>required</strong>
                </mat-error>
                </div>

                <pre>id.errors: id.errors </pre>


                From here you will need to use @ViewChild in your component to get reference to #id and call markAsTouched() on the control via ngOnInit life cycle hook.



                import Component, OnInit, ViewChild from '@angular/core';

                @ViewChild('id') _id : any

                ngOnInit()
                this._id.control.markAsTouched();






                share|improve this answer



























                  0












                  0








                  0







                  If you are willing to use reactive forms... using ngAfterViewInit, you could programmatically mark the field as touched to force the error.




                  • Unfortunately I am not familiar with how to accomplish this via
                    template driven forms.



                    setTimeout(() => 
                    this.yourForm.controls['yourControl'].markAsTouched();
                    , 0);


                  Revision



                  Based on my original answer, and the expansion of my answer by Abhishek to re-enforce that you can do this with reactive forms... I wanted to provide the template driven form scenario as well.



                  • The common theme here, regardless if you use reactive forms or template driven forms is that, you need to programmatically mark the
                    input as touched...

                  • In template driven forms you will also need to do
                    the same via template reference so that you can call the markAsTouched() method on the control in
                    your ngOnInit life cycle hook.

                  Set a template reference of id and bind it to ngModel via #id="ngModel" on the input... you will also need to assign a name on the input of id via name="id" this is a requirement of binding to ngModel.



                  <mat-form-field color="accent">
                  <input matInput placeholder="ID is required" required="true" [(ngModel)]="uniqueID" name="id" #id="ngModel">
                  </mat-form-field>

                  <div *ngIf="id.invalid && (id.dirty || id.touched)">
                  <mat-error *ngIf="id.errors.required">
                  ID is <strong>required</strong>
                  </mat-error>
                  </div>

                  <pre>id.errors: id.errors </pre>


                  From here you will need to use @ViewChild in your component to get reference to #id and call markAsTouched() on the control via ngOnInit life cycle hook.



                  import Component, OnInit, ViewChild from '@angular/core';

                  @ViewChild('id') _id : any

                  ngOnInit()
                  this._id.control.markAsTouched();






                  share|improve this answer















                  If you are willing to use reactive forms... using ngAfterViewInit, you could programmatically mark the field as touched to force the error.




                  • Unfortunately I am not familiar with how to accomplish this via
                    template driven forms.



                    setTimeout(() => 
                    this.yourForm.controls['yourControl'].markAsTouched();
                    , 0);


                  Revision



                  Based on my original answer, and the expansion of my answer by Abhishek to re-enforce that you can do this with reactive forms... I wanted to provide the template driven form scenario as well.



                  • The common theme here, regardless if you use reactive forms or template driven forms is that, you need to programmatically mark the
                    input as touched...

                  • In template driven forms you will also need to do
                    the same via template reference so that you can call the markAsTouched() method on the control in
                    your ngOnInit life cycle hook.

                  Set a template reference of id and bind it to ngModel via #id="ngModel" on the input... you will also need to assign a name on the input of id via name="id" this is a requirement of binding to ngModel.



                  <mat-form-field color="accent">
                  <input matInput placeholder="ID is required" required="true" [(ngModel)]="uniqueID" name="id" #id="ngModel">
                  </mat-form-field>

                  <div *ngIf="id.invalid && (id.dirty || id.touched)">
                  <mat-error *ngIf="id.errors.required">
                  ID is <strong>required</strong>
                  </mat-error>
                  </div>

                  <pre>id.errors: id.errors </pre>


                  From here you will need to use @ViewChild in your component to get reference to #id and call markAsTouched() on the control via ngOnInit life cycle hook.



                  import Component, OnInit, ViewChild from '@angular/core';

                  @ViewChild('id') _id : any

                  ngOnInit()
                  this._id.control.markAsTouched();







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 16 '18 at 7:41

























                  answered Nov 15 '18 at 22:01









                  MarshalMarshal

                  2,9822419




                  2,9822419



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53328049%2fmat-form-field-always-show-required-red-color%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Top Tejano songwriter Luis Silva dead of heart attack at 64

                      ReactJS Fetched API data displays live - need Data displayed static

                      政党