gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:13:30 25 4
gpt4 key购买 nike

在我的 Angular 4 项目中,我必须在没有任何绑定(bind)的情况下在输入字段和 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
}

我无法访问值,为什么?我怎样才能访问它?

最佳答案

您可以访问输入元素如下

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

它是 Angular ,然后你只需将你的输入与模板属性绑定(bind)并赋值

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

然后在 ts 文件中这样做

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

我没有得到你正在使用 angularjs2 和 typescript 的一件事,你正试图通过 document.getElementById 获取元素值,是不是出了什么问题??

因为 Component 自带模板和 .ts 模板代码文件..你很容易实现这个功能。

关于angular - 在 Angular 4 的 html 字段中设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47810487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com