Reputation: 4503
I'm learning Angular 6 and when learning how to pass data from a parent component into a child component it was shown that we should add an Input() property into the child which is what the parent will populate.
My question was, if i'm just creating a component with a property, like elementId, that it going to be set when i use the element. It will not be passed into it from another component, but hardcoded like:
<my-component elementId='xyz'>
the guide i'm seeing is creating that elementId as an Input() in the component. I thought earlier guides i read never did that, it was just declared as a regular property in the component class, without the Input()
Is the Input() always needed, or just when passing data from parent into child?
I have included the code the author used:
import { Component, OnInit, Input } from '@angular/core';
import { Title } from '@angular/platform-browser';
@Component({
selector: 'simple-modal',
templateUrl: './simple-modal.component.html',
styleUrls: ['./simple-modal.component.css']
})
export class SimpleModalComponent implements OnInit {
@Input() title: string;
@Input() elementId: string;
constructor() { }
ngOnInit() {
}
closeModal() {
}
}
Component is used within another component as:
<simple-modal elementId="searchResults" title="Matching Sessions">
<div class="list-group">
<a class="list-group-item" *ngFor="let session of foundSessions" [routerLink]="['/events', session.eventId]">{{session.name}}</a>
</div>
</simple-modal>
Upvotes: 0
Views: 1071
Reputation: 1023
The @Input
decorator will create a binding for the property (in your case elementId), therefore it will be checked in every change detection cycle.
If your property will never change, there is an alternative: @Attribute
decorator, which is read just once.
You may use it this way:
import { Component, Attribute } from '@angular/core';
@Component({
selector: 'my-component',
template: `<label>{{ elementId }}</label>`
})
export class MyComponent {
constructor(@Attribute('elementId') public elementId: string) { }
}
Upvotes: 0
Reputation: 16167
This is one of those cases where the answer is "because that's what the documentation says."
Angular requires the Input()
directive for template binding to component properties. Angular does not make a distinction between a "hard-coded" value and a dynamic value. If you want to supply the value of a child component from a template parent, you have to use Input()
decorator.
Frankly, even if you could get away without the Input()
decorator, this would almost certainly be a programming mistake and would be horrible design practice.
Upvotes: 0
Reputation: 32517
Input allows you to do bindings in template (in HTML markup, not in OOP manner). They are updated in async way and updating such input will invoke onChange
callback. You cant have that with simple property.
EDIT:
Out of curiosity I have checked your statement and the answer is NO, it wont be set. https://stackblitz.com/edit/angular-xtkgt4
Upvotes: 3