【问题标题】:How can I get value of HTML tags and use them in Angular 2 component?如何获取 HTML 标签的值并在 Angular 2 组件中使用它们?
【发布时间】:2018-01-21 01:52:23
【问题描述】:

我是 Angular 2 的新手,对它的语法不太熟悉。我有一个表单,在 html 页面中有输入和选择,就像这些。

它们中的大多数没有任何组件,只是 HTML 标记中的值。但我想从 HTML 中获取这些值并在我的组件中使用它们。我搜索了很多但没有成功。如何在 HTML 和 ts 页面中编写所需的任何内容?

例如,这是我的表单的一部分:

<select class="form-control " id="sel1">
                        <option disabled>type</option>
                        <option>apartment</option>
                        <option>store</option>
                        <option>villa</option>
                        <option>ofiice</option>
                    </select>

我应该注意到,当我想问这个问题时,我在 bur 之前搜索过,但没有得到答案。

【问题讨论】:

  • 所以你搜索了“Angular form”并没有得到任何东西?因为那里有 大量 信息,来自官方文档和其他地方。例如:angular.io/guide/forms
  • 应该反过来,你应该在你的 Angular 组件中有这些值,然后在 HTML 中使用它们。
  • @tima 你确定没有别的办法吗?
  • @AmirGh 另一种方法是以某种方式将 HTML 加载到字符串或文件中,然后在 Angular 中解析它以获取值。可以做到,但这不是一个好方法。
  • @tima 好的,谢谢

标签: angular data-binding


【解决方案1】:

经过这么多搜索,我找到了答案: 对于 html 页面中的 select 和 option 标签:

<select #selecttypes>
                    <option disabled>type</option>
                    <option *ngFor="let type of types" [value]="type.id">{{type.name}}</option>
</select>
<button (click)=onSubmit($event,selecttypes)>Submit</button>

例如,您希望将这些值放在具有 typeofbuilding 属性的 Building 类中。 并在 component.ts 中:

import {Building} from './building';
export class Component {
constructor(private building: Building) {}
types: any[] = [
{id:1,name:'Apartment'},
{id:2,name:'Store'},
{id:3,name:'Villa'},
{id:4,name:'Office'},
];
onSubmit($event: any,selecttypes: string){
$event.preventDefault();
this.building.typeofbuilding= selecttypes;
console.log(this.building.typeofbuilding)
 }
}

对于输入标签: 在html页面中:

<input #rooms name="username" type="text" required>
<button (click)="onSubmit($event,rooms.value)>Submit</button>

Building 类中还有另一个属性 numofrooms。所以 component.ts 是:

import {Building} from './building';
export class Component {
constructor(private building: Building) {}
onSubmit($event: any,rooms: number){
$event.preventDefault();
this.building.numofrooms= rooms;
console.log(this.building.numofrooms)
 }
}

希望对你有用。

【讨论】:

    猜你喜欢
    • 2016-06-26
    • 2018-09-08
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 2018-07-28
    相关资源
    最近更新 更多