Поділитися тим, що мені вдалося:
Додавання вхідних даних до програми Angular 4
Припускаючи, що у нас є 2 компоненти:
parent-component
child-component
Ми хотіли передати якесь значення від parent-componentдо child-componentтобто тобто @Inputвід parent-component.htmlдо 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);
}
ngOnInit() {
console.log('someInputValue in ngOnInit ************** ', this.someInputValue);
}
}
Зверніть увагу, що значення @Inputзначення доступне всередині, ngOnInit()а не всередині constructor().
Поведінка об'єктів у Angular 2/4
У Javascript об'єкти зберігаються як посилання .
Цю точну поведінку можна відтворити за допомогою Angular 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);
}
ngOnInit() {
console.log('someInputValue in ngOnInit ************** ', this.someInputValue);
}
changeInput(){
this.someInputValue.input += " changed";
}
}
Функція changeInput()змінить значення someInputValueвсередині обох ChildComponent& ParentComponentчерез їх посилання. Так, someInputValueпосилаються з ParentComponent«S someInputValue об'єкта - зміна ChildComponent» s someInputValue об'єкта змінює значення ParentComponent«s someInputValue об'єкта . ЦЕ НЕ ПРАВИЛЬНО . Посилання ніколи не змінюються.