gpt4 book ai didi

angular - 如何在 Angular 中设置来自服务的输入模型值?

转载 作者:行者123 更新时间:2023-12-05 03:10:47 24 4
gpt4 key购买 nike

这里的问题是如何在 Angular 2 中设置来自服务的输入模型值。

这是我的示例代码:
组件:

//our root app component
import {Component} from 'angular2/core'
import {Service} from './service'

@Component({
selector: 'my-directive',
providers: [],
template: `<input [(ngModel)]="abc">`,
directives: []
})
export class Directive {
constructor(public service: Service) {
this.abc = this.service.value;
}
}

服务:

//我们的根应用组件从 'angular2/core' 导入 {Injectable}

@Injectable()
export class Service {
constructor() {
this.value = "service"
}
abcFun(){
// need to update value from here
}
}

plunkr here

最佳答案

试试这个:

component.html

<input type="text" [(ngModel)]="abc">

component.ts

private abc: string;

constructor(
public homeService: HomeService
) { }
ngOnInit() {
this.abc = this.homeService.value;
}

component.service.ts

public value: string;

constructor(private http: Http) {
this.value = "Hello world";
}

关于angular - 如何在 Angular 中设置来自服务的输入模型值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38727314/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com