Angular 角度:如何使用多个条件设置[占位符]
如何根据多个可能的值设置占位符? 我试过这个:Angular 角度:如何使用多个条件设置[占位符],angular,typescript,Angular,Typescript,如何根据多个可能的值设置占位符? 我试过这个: [占位符]=”{ '在此处键入您的答案…':question.Type=='text', 'address@example.com“:question.type==”电子邮件“, '00':question.type=='phone' }" 但这不起作用,并在输入字段中显示[object object]。占位符属性不接受像ngClass那样的对象,它需要字符串。您可以在组件上创建一个方法,该方法根据问题类型返回适当的字符串 private pla
[占位符]=”{
'在此处键入您的答案…':question.Type=='text',
'address@example.com“:question.type==”电子邮件“,
'00':question.type=='phone'
}"
但这不起作用,并在输入字段中显示
[object object]
。占位符属性不接受像ngClass
那样的对象,它需要字符串。您可以在组件上创建一个方法,该方法根据问题类型返回适当的字符串
private placeholders: { [key: string]: string } = {
text: 'Type your answer here...',
email: 'address@example.com',
phone: '00 00 00 00 00'
};
public getPlaceholder(questionType: string): string {
return this.placeholders[questionType] || 'Default placeholder';
}
在模板中使用它,如下所示:
[placeholder]="getPlaceholder(question.type)"
您应该将逻辑代码移动到ts文件中,创建方法以将占位符返回为
getPlaceHolder() {
if (this.question.type === "text") return "Type your answer here...";
if (this.question.type === "email") return "address@example.com";
if (this.question.type === "phone") return "00 00 00 00 00";
}
输入标签
<input type="text" [placeholder]="getPlaceHolder()" />
演示?如果您公开对象“占位符”,您可以直接使用