Angular 无法将用户输入从 html 传递给打字稿
Angular can't get user input passed to typescript from html
html
<input #box (keyup.enter)="Character(box.value)"/>
打字稿
Character(value: string) {
console.log("print this " + value);
}
我在网上的两个不同地方确认了 typescript 代码,并从此处的另一个答案中获得了 html 代码,即使 typescript 函数执行 "value" 也不会打印到控制台.我什至改变了我的浏览器主题,认为这在某一时刻会产生干扰。 (因为它改变了文本框的颜色和一些网站文本与框混合)
Update 从所选答案可以看出,我没有意识到我的问题是我有两个导致问题的文本框,因为值不仅仅是正如我假设的那样过去了。
您可以做的是将您的输入包裹在表单标签中,例如:
<form (ngSubmit)="submit()">
<input type="text" [(ngModel)]="name" name="name">
</form>
在打字稿中:
name = '';
submit() {
console.log(this.name);
}
这按预期工作:
参考:https://stackblitz.com/edit/angular-jcrcdu?file=src%2Fapp%2Fapp.component.html
app.component.html
<input #box (keyup.enter)="Character(box.value)"/>
<p>{{box1name}}</p>
<input #box2 (keyup.enter)="onEnter(box2.value)"/>
<p>{{box2name}}</p>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
box1name = 'Angular';
box2name = 'Angular2';
Character(value: string) {
this.box1name="print this for box1 :" + value;
console.log(this.box1name);
}
onEnter(value: string) {
this.box2name="print this for box2: " + value;
console.log(this.onEnter);
}
}
html
<input #box (keyup.enter)="Character(box.value)"/>
打字稿
Character(value: string) {
console.log("print this " + value);
}
我在网上的两个不同地方确认了 typescript 代码,并从此处的另一个答案中获得了 html 代码,即使 typescript 函数执行 "value" 也不会打印到控制台.我什至改变了我的浏览器主题,认为这在某一时刻会产生干扰。 (因为它改变了文本框的颜色和一些网站文本与框混合)
Update 从所选答案可以看出,我没有意识到我的问题是我有两个导致问题的文本框,因为值不仅仅是正如我假设的那样过去了。
您可以做的是将您的输入包裹在表单标签中,例如:
<form (ngSubmit)="submit()">
<input type="text" [(ngModel)]="name" name="name">
</form>
在打字稿中:
name = '';
submit() {
console.log(this.name);
}
这按预期工作:
参考:https://stackblitz.com/edit/angular-jcrcdu?file=src%2Fapp%2Fapp.component.html
app.component.html
<input #box (keyup.enter)="Character(box.value)"/>
<p>{{box1name}}</p>
<input #box2 (keyup.enter)="onEnter(box2.value)"/>
<p>{{box2name}}</p>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
box1name = 'Angular';
box2name = 'Angular2';
Character(value: string) {
this.box1name="print this for box1 :" + value;
console.log(this.box1name);
}
onEnter(value: string) {
this.box2name="print this for box2: " + value;
console.log(this.onEnter);
}
}