分享了什么工作对我来说:
添加一个输入角4应用
假设我们有两个部分组成:
parent-component
child-component
我们想从parent-component
一些价值从parent-component.html
传递到child-component
即一个@Input
到child-component.ts
。下面是说明执行情况的例子:
parent-component.html
看起来是这样的:
<child-component [someInputValue]="someInputValue"></child-component>
parent-component.ts
看起来是这样的:
class ParentComponent {
someInputValue = 'Some Input Value';
}
child-component.html
看起来是这样的:
<p>Some Input Value {{someInputValue}}</p>
child-component.ts
看起来是这样的:
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'child-component',
templateUrl: './child-component.html'
})
export class ChildComponent implements OnInit {
@Input() someInputValue: String = "Some default value";
@Input()
set setSomeInputValue(val) {
this.someInputValue += " modified";
}
constructor() {
console.log('someInputValue in constructor ************** ', this.someInputValue); //someInputValue in constructor ************** undefined
}
ngOnInit() {
console.log('someInputValue in ngOnInit ************** ', this.someInputValue); //someInputValue in ngOnInit ************** Some Input Value
}
}
注意,@Input
值的值可用内ngOnInit()
,而不是内部constructor()
。
对象引用在角2/4
在Javascript中的行为,对象存储为references。
这个确切的行为可以被重新制作,具有角2/4,下列的说明是解释执行的例子:
parent-component.ts
看起来是这样的:
class ParentComponent {
someInputValue = {input: 'Some Input Value'};
}
parent-component.html
看起来是这样的:
{{someInputValue.input}}
child-component.html
看起来是这样的:
Some Input Value {{someInputValue}}
change input
child-component.ts
看起来是这样的:
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'child-component',
templateUrl: './child-component.html'
})
export class ChildComponent implements OnInit {
@Input() someInputValue = {input:"Some default value"};
@Input()
set setSomeInputValue(val) {
this.someInputValue.input += " set from setter";
}
constructor() {
console.log('someInputValue in constructor ************** ', this.someInputValue); //someInputValue in constructor ************** undefined
}
ngOnInit() {
console.log('someInputValue in ngOnInit ************** ', this.someInputValue); //someInputValue in ngOnInit ************** Some Input Value
}
changeInput(){
this.someInputValue.input += " changed";
}
}
功能changeInput()
会改变,因为他们参考的someInputValue
都ChildComponent
& ParentComponent
内的值。因为,someInputValue
从ParentComponent
引用的someInputValue
对象 - 在ChildComponent
变化的someInputValue
对象改变ParentComponent
的someInputValue
对象的值。 这是不正确的。引用永远不会改变。
不要在模板中使用驼峰名。 HTML不区分大小写。 – alexpods
谢谢alex!我想我必须改变这种习惯。 ; 0) – Zorthgo