TIL, 2022-09-26, ViewChild selectors
What are all the valid selectors for ViewChild and ContentChild?
- Angular Directive -
@ViewChild(NgModel) filterInput: NgModel;
- Custom directive/child component:
@ViewChild(StarComponent) star: StarComponent;
- Template reference variable:
@viewChild('divElementVar') divElementRef: ElementRef;
. BTW this can 2 or more strings. - The actual place where Angular returns the value of a query: Reference
- You can access another component’s
@ViewChild
Reference
@ViewChild(SharkDirective)
set appShark(directive: SharkDirective) {
this.extraCreature = directive.creature;
};
- If the reference changes to a new element dynamically, ViewChild will automatically update its reference.
What is the read parameter in @ViewChild for
- If you don’t provide the read parameter,
@ViewChild()
returns the- ElementRef instance if there is no component applied, or the
- component instance if there is.
- If you want to get something different you need to explicitly specify using read.
Angular @ViewChild: In-Depth Explanation (All Features Covered)
- We need ViewChild when the AppComponent might need references to the multiple elements that it contains inside its template, in order to mediate their interaction.
- AfterViewInit vs OnInit: We should always write our initialization code using
ngAfterViewInit()
. With@ViewChild
, we can inject any component or directive present on the template of a given component onto the component itself.
Is there a way to check for @Output wire up from within a component in Angular?
import {Component, Output, EventEmitter} from '@angular/core';
@Component({
selector: 'sample',
template: `<p>a sample</p>`
})
export class SampleComponent {
@Output() cancel = new EventEmitter();
private isCancelUsed = false;
ngOnInit() {
this.isCancelUsed = this.cancel.observed;
}
}
ARIA attributes as CSS selectors
- We can do something like this:
.co-Button {
&[aria-selected="true"] {
background-color: $color-button-selected;
}
}
enable/disable form control fires valueChanges Angular 2 Forms
form.controls['firstName'].enable({ emitEvent: false });