Search code examples
angularviewchild

How to make ViewChild to set a property instead of a variable


I have a Class. And a property of this Class is named model_number. What I'm trying to do here is to set an attribute "DOMelement" of this property with the ViewChild.

The code :

import {Component,ViewChild} from '@angular/core';
@Component({
    selector: 'app-form',
    templateUrl: './form.component.html',
    styleUrls: ['./form.component.scss']
})
export class FormComponent  {
    @ViewChild('model_number') model_number.DOMelement:ElementRef;
    model_number = {value: '', api_name: 'hardware_model_number', required: true,element:{}};
}

But it fails to compile with a nice syntax error. How can I achieve this :

 @ViewChild('model_number') model_number.DOMelement:ElementRef;

Solution

  • I found a way, but it feels excessive if someone finds another way I'm all ears.

    here is my take on this problem :

    import {Component,ViewChild} from '@angular/core';
    @Component({
        selector: 'app-form',
        templateUrl: './form.component.html',
        styleUrls: ['./form.component.scss']
    })
    export class FormComponent  implements AfterViewInit{
        @ViewChild('model_number') model_number_DE:ElementRef;
    
        model_number = {value: '', api_name: 'hardware_model_number', required: true,element:{}};
        ngAfterViewInit() {
            this.model_number.element = this.model_number_DE.nativeElement;
        }
    }