Bodrov
Bodrov

Reputation: 867

Unable to pass value from component to template

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>

Upvotes: 0

Views: 169

Answers (1)

Emilien
Emilien

Reputation: 2761

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.

Upvotes: 3

Related Questions