Home > Software design >  Unable to pass value from component to template
Unable to pass value from component to template

Time:12-08

I've defined a variable, MIN_PW, above my component's export class MyComponent, and although the intellisense recognizes it in my formBuilder it's not appearing in the UI properly (UI shows "Password must contain at least characters").

Originally I'd defined the variable within export class and it was working, but I was advised to set it with const and move it above the component.

Component file:

const MIN_PW = 12;

export class MyComponent implements OnInit {

  myFormGroup = this.formBuilder.group({
      password: new FormControl(null, [Validators.required, Validators.minLength(MIN_PW)]),
      // etc
  )

}

Template file:

<mat-form-field class="password-field">
<mat-error *ngIf="myFormGroup.controls['password'].invalid">Password must contain at least {{MIN_PW}} characters.</mat-error>
</mat-form-field>

CodePudding user response:

I would suggest to declare all of your constants in a separated file, which you will import wherever you want.

To me, the following approach seems more straight forward for your case:

  1. Define and export your constants in one or multiple TS files.
  2. Import the constants using import { MY_CONSTANT } from '../constants/my-constant.ts'; where ever you need them.
  3. Use them and be happy.
  • Related