Reputation: 4209
In my angular 4 project I have to set some value in input field and in a MatSelect without any binding.
This is the HTML
<div class="row search-component">
<div class="col-md-5 no-padding-right">
<mat-form-field>
<mat-select placeholder="searchfor" id="selectedFilter" name="propertyList" #selectedFilter>
<mat-option *ngFor="let property of propertyList" [value]="property">
{{property.label}} </mat-option>
</mat-select>
</mat-form-field>
</div>
<div class="col-md-7 no-padding-left">
<mat-form-field>
<input matInput placeholder="search" id="searchfield" name="searchfield" #selectedValue>
<mat-icon class="pointer" matSuffix>search</mat-icon>
</mat-form-field>
</div>
</div>
When I click in a button I have to set a Mat-option and a value in the input field.
This is the method Who have to set the values:
setField(chipSelected: Filter) {
this.filter = chipSelected;
document.getElementById('searchfield').focus();
document.getElementById('searchfield').value = 'somevalue'; <-- I can't use this instruction
}
I can't access to value, Why? And how can I access to it?
Upvotes: 2
Views: 38661
Reputation: 176956
you can access input element as below
<input #someInput placeholder="test input">
import { AfterViewInit,ElementRef } from '@angular/core';
export class AppComponent implements AfterViewInit {
@ViewChild('someInput') someInput: ElementRef;
ngAfterViewInit() {
this.someInput.nativeElement.value = "update input value";
}
}
its angular, then you just bind you input with the template property and assign value
<input matInput [(ngModel)] = "searchFor" placeholder="search"
id="searchfield" name="searchfield" #selectedValue>
then in ts file jus do like this
setField(chipSelected: Filter) {
///your code
this.searchFor='somevalue';
}
I am not geting one thing you are making use of angularjs2 and typescript and you are trying to get element value by document.getElementById
, is something wrong ??
because Component comes with template and .ts template code file ..and you achieve this functionality easily.
Upvotes: 6
Reputation: 5394
Ohh, I guess that you are new in Angular world. I suggest you to read something about ngModel
and data binding in angular (here a link). Using native JS methods like .getElementId()
is a horrible idea. F.e. the better solution is use ngModel for your input in way:
<input matInput placeholder="search" [(ngModel)]="someValue" id="searchfield" name="searchfield">
declare cariable in your component:
someValue: string;
and in your method use:
setField(chipSelected: Filter) {
this.someValue = 'somevalue';
}
Upvotes: 0