我正在学习Angular 2.为此,我试图通过点击按钮获得输入的值。
这是我的代码:
bucket.s3.amazonaws.com
并在模板中:
import { Component, Input } from '@angular/core'
import Card from './card.component'
import CardTitle from './cardTitle.component'
import Icon from './icon.component'
import CardDescription from './cardDescription.component'
@Component({
selector: 'jsonTextInput',
templateUrl: '../templates/jsonTextInput.html',
directives: [Card, CardTitle, CardDescription, Icon]
})
export class JsonTextInput {
@Input() ngModel: any;
process () {
console.log(this.ngModel)
alert(1);
}
}
正在正确运行该流程。但是<card class='jsonTextInput'>
<cardtitle
title='Enter your raw json'
>
<icon (click)='process()' name='tick'></icon>
</cardtitle>
<carddescription>Write or paste your json here, and press Process to start navigating</carddescription>
<section class='content'>
<textarea #json [(ngModel)]="json"></textarea>
</section>
</card>
返回console.log
。
如何知道如何在点击按钮时读取输入的值?
答案 0 :(得分:1)
也许你没有正确使用输入和其他东西,让我解释一下。
输入用于将数据以属性形式注入组件,如下所示:
<jsonTextInput [my-input]="'this is a text :D'"></jsonTextInput>
您可以在组件中获取这样的数据:
import { Component, Input } from '@angular/core'
import Card from './card.component'
import CardTitle from './cardTitle.component'
import Icon from './icon.component'
import CardDescription from './cardDescription.component'
@Component({
selector: 'jsonTextInput',
templateUrl: '../templates/jsonTextInput.html',
directives: [Card, CardTitle, CardDescription, Icon]
})
export class JsonTextInput {
@Input('my-input') myInput: any; //Here es saved: "this is a text :D"
json:String = "Hi i'm a message"; //You must declarate all models in the component
process () {
console.log(this.myInput); //this print: "this is a text :D"
alert(1);
}
}
现在,对于打印,textarea中的文本是这样的:
process () {
console.log(this.json); //this print: "Hi i'm a message"
alert(1);
}
您的模板必须如下:
<card class='jsonTextInput'>
<cardtitle
title='Enter your raw json'
>
<icon (click)='process()' name='tick'></icon>
</cardtitle>
<carddescription>Write or paste your json here, and press Process to start navigating</carddescription>
<section class='content'>
<textarea [(ngModel)]="json"></textarea><!-- You only need #json if you are working whit forms -->
</section>
</card>
这就是全部。
答案 1 :(得分:0)
我会将此作为答案发布,而不仅仅是评论。
在课堂内添加一个本地var:
json:string = ''; // This will set the textarea blank.
在您的流程功能更改中:
console.log(this.ngModel);
要
console.log(this.json);
服务你的页面,在textarea中输入文字,点击按钮,瞧!登录
史蒂夫