0

Is there a way of creating #-variables to HTML elements dynamically with *ngFor?

E.G

html-file

<mat-checkbox #{{name}} *ngFor="let name of names" (click)="matBoxClick({{name}})"></mat-checkbox>

ts-file

@ViewChild('checkbox1') private checkbox1:MatCheckbox;
@ViewChild('checkbox2') private checkbox2: MatCheckbox;
@ViewChild('checkbox3') private checkbox3: MatCheckbox;
@ViewChild('checkbox4') private checkbox4: MatCheckbox;

...

names = [
'checkbox1',
'checkbox2',
'checkbox3',
'checkbox4'
];

...

matBoxClick(name) { 
   console.log(this[name])
}

Whit this code, the console.log prints undifined. If I put the name directly as the variable name, the ts-file is able to find it.

<mat-checkbox #checkbox1 (click)="matBoxClick({{name}})"></mat-checkbox>

The problem seems to come with *ngFor. Any suggestions how I could accomplish this? Thanks for help.

Leero11
  • 365
  • 2
  • 4
  • 17
  • `console.log(this[name])` should print undefined, why wouldnt it? – mast3rd3mon Aug 15 '18 at 10:46
  • Shouldn't it print the mat-checkbox element that has the same variable name? – Leero11 Aug 15 '18 at 10:49
  • nope, it looks for a variable/function/property within the class in the .ts file called whatever `name` is at the time – mast3rd3mon Aug 15 '18 at 10:50
  • How can I then bind the variable in the HTML-file to the variable in the ts-file? If I place the #checkbox1 variable straight to the HTML-file, the ts-file is able to find the correct element. The problem seems to come with *ngFor. – Leero11 Aug 15 '18 at 10:53
  • 1
    why do you need to? is it to get the value of it? – mast3rd3mon Aug 15 '18 at 10:53
  • I want to be able to toggle the checked attribute of mat-checkbox, by clicking another HTML-element. And this seems to be surprisingly difficult, because I cannot cast a HTML element as a MatCheckbox. – Leero11 Aug 15 '18 at 10:56
  • you may need to used checked, see this https://stackoverflow.com/questions/40214655/angular-2-checkbox-two-way-data-binding – hamilton.lima Aug 15 '18 at 15:29

0 Answers0