简体   繁体   中英

(Angular) How can I get the #tag definition in html to Javascript?

I am having difficulty working on an Angular project.

In HTML...

<input #abc>...</input>

In Javascript

let var = ... *(how can i get the input element 'abc' to javascript?)*

I know it's too basic, I am having a lot of trouble. Help!

you can refererence it with a @VhiewChild('abc') myInput: ElementRef; . however if you want JUST value more valid and easy way to make a field on you class, lets say value and update it when your input updates <input (input)="value = $event.target.value" [value]="value">

this a template reference, you need to grab this element using @ViewChild decorator

@Component({
    template:" <input #abc>...</input> "
})
export class SomeComponent implements AfterViewInin{

    @ViewChild("abc")
    element:ElementRef<HtmlElement>;

    ngAfterViewInit(){
       console.log(this.element.nativeElement);
    }

}

I encourage you to read, the following topics to get the knowledge for that https://angular.io/guide/component-interaction#parent-calls-an-viewchild for viewChild https://angular.io/guide/template-syntax#template-syntax for template reference

if you use event

<input #abc (click)="getabc(abc)">...</input>

getabc(element) { console.log(abc) } //element input

if just get in.ts

@ViewChild("abc") element:ElementRef<HtmlElement>;

you can get element .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM