【发布时间】:2020-01-20 13:48:06
【问题描述】:
我是 Angular 新手。
我有 form-control.component.ts 文件 因为我已经全局声明了这 3 个变量
name1:any;
pw :any';
g :any;
我在一个函数中使用了这 3 个变量
displayAccountInfo(account:Account)
{
this.name1=account.name;
this.pw=account.password;
this.g=account.gender;
}
我想在 ClickMe() 函数中显示这 3 个变量的值
result:string;
ClickMe():void {
this.result =' *saved dataItems: ' + this.name1 +this.pw +this.g ;
}
但我得到了这些输出
*saved dataItems: undefined undefined undefined
我必须在 displayAccountInfo() 函数中显示分配给这些变量的值
我在 Save 方法中调用了 displayAccountInfo()
Save():void{
let account:Account=this.registerform.value;
account.languages=this.checkedList;
this.displayAccountInfo(account);
}
这是整个文件
import { Component, OnInit } from '@angular/core';
import {Account} from './account.entity'
import { FormGroup, FormBuilder, FormControl } from '@angular/forms';
@Component({
selector: 'app-form-control',
templateUrl: './form-control.component.html',
styleUrls: ['./form-control.component.css']
})
export class FormControlComponent implements OnInit {
genders:any;
languages:any;
registerform:FormGroup;
checkedList:string[];
certificates:any;
name1:any;
pw :any;
g :any;
constructor(
private formbuilder:FormBuilder) { }
ngOnInit() {
this.checkedList=[];
this.certificates=[
{value:'c1' ,display: 'Microsoft'},
{value:'c2' ,display: 'Oracle'},
{value:'c3' ,display: 'Angular'},
{value:'c4' ,display: 'Java'},
];
this.genders=[
{value:'F' ,display:'Female'},
{value:'M' ,display:'Male'}
];
this.languages=[
{id:'1' ,name:'C#'},
{id:'2' ,name:'Java'},
{id:'3' ,name:'typescript'},
{id:'4' ,name:'Html'}
];
this.registerform=this.formbuilder.group({
name:'',
password:'',
gender:this.genders[0].value,
languages:[],
certificates:[]
});
}
Save():void{
let account:Account=this.registerform.value;
account.languages=this.checkedList;
this.displayAccountInfo(account);
}
displayAccountInfo(account:Account)
{
this.name1=account.name;
this.pw=account.password;
this.g=account.gender;
for(var i=0; i< account.languages.length; i++)
{
var lang=account.languages[i];
}
for(var j=0; j< account.certificates.length; j++)
{
var cer=account.certificates[i];
}
}
Checkboxchange(option,event)
{
if(event.target.checked)
{
this.checkedList.push(option.id);
}
else
{
for(var i=0;i<this.languages.length;i++)
{
if(this.checkedList[i]==option.id)
{
this.checkedList.splice(i,1);
}
}
}
}
result:string;
ClickMe():void {
this.result =' *saved dataItems: ' + this.name1 +this.pw +this.g ;
}
}
【问题讨论】:
-
可能你没有先调用displayAccountInfo?
-
你能分享你的整个formcontrol.ts吗?您的代码看起来非常非结构化,这不是您应该使用 angular 的方式。
-
如果有东西被点击和显示,那是一个组件的任务。所以代码应该在一个组件(some.component.ts)中,在那个组件类中,你应该更改 3 个变量 name1、pw 和 g。您根本不应该为此使用全局变量。
-
我的代码在 @Robin De Schepper 的 form-control.component.ts 文件中
-
好的,谢谢,您能否通过在
displayAccountInfo末尾添加一个console.log 来确认this.name1、this.pw和this.g属性设置为您期望的值?因为您发送的account可能不是您认为的值。
标签: angular angular-directive angular8 angular4-forms