【发布时间】:2018-05-16 09:27:56
【问题描述】:
我想将带有 ngModel(2 路绑定)的服务变量绑定到组件输入。因此,我使用简单的返回函数来返回服务变量(这是从服务中获取正确变量所必需的)。
但如果我想运行此代码,我会收到以下错误:
Template parse errors:
Parser Error: Unexpected token '=' at column 10 in [getName()=$event] in ng:///AppModule/HelloComponent.html@2:9 ("
{{nameService.name}}
你好,在我的案例中,它是更复杂的例子。为了简化这一点,我做了以下示例和演示:https://stackblitz.com/edit/angular-hwgoux?file=src%2Fapp%2Fhello.component.ts
服务:
import { Injectable } from '@angular/core';
@Injectable()
export class NameService {
name:string="Hello World!";
constructor() { }
getName(){return this.name};
}
组件:
import { Component, Input } from '@angular/core';
import { NameService} from './name.service';
@Component({
selector: 'hello',
template: `
{{nameService.name}}
<input [(ngModel)]="getName()">`
})
export class HelloComponent {
@Input() name: string;
constructor(private nameService:NameService){
}
getName(){
return this.nameService.getName();
}
}
【问题讨论】: