首页 文章

在Angular 4中的html字段中设置值

提问于
浏览
0

在我的angular 4项目中,我必须在输入字段和MatSelect中设置一些值而不进行任何绑定 .

这是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>

当我单击一个按钮时,我必须在输入字段中设置Mat选项和值 .

这是必须设置值的方法:

setField(chipSelected: Filter) {
    this.filter = chipSelected;
    document.getElementById('searchfield').focus();
    document.getElementById('searchfield').value = 'somevalue'; <-- I can't use this instruction
  }

我无法获得 Value ,为什么?我怎样才能访问它?

2 回答

  • 2

    您可以访问input元素,如下所示

    <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";
      }
    }
    

    它的角度,然后您只需使用模板属性绑定输入并指定值

    <input matInput [(ngModel)] = "searchFor" placeholder="search" 
          id="searchfield" name="searchfield" #selectedValue>
    

    那么在ts文件中jus就是这样的

    setField(chipSelected: Filter) {
    ///your code
     this.searchFor='somevalue';
    }
    

    我没有说你正在使用angularjs2和typescript,你试图通过 document.getElementById 得到元素值,是不是错了?

    因为Component附带了模板和.ts模板代码文件..您可以轻松实现此功能 .

  • 0

    哦,我猜你是Angular世界的新手 . 我建议你阅读 ngModel 和有角度的数据绑定(here a link) . 使用像 .getElementId() 这样的原生JS方法是一个可怕的想法 . F.E.更好的解决方案是使用ngModel进行输入:

    <input matInput placeholder="search" [(ngModel)]="someValue" id="searchfield" name="searchfield">
    

    在你的组件中声明cariable:

    someValue: string;
    

    并在您的方法中使用:

    setField(chipSelected: Filter) {
        this.someValue = 'somevalue';
    }
    

相关问题