I try to create custom component which looks like search form. I have created SearchComponent
with selector my-search
inside of which I have placed HTML <input>
element with attached directive InputDirective
with selector [myInput]
:
<my-search>
<input myInput>
</my-search>
The issue is how to detect changes from InputDirective
inside of SearchComponent
? For example: I should enable or disable button when user types some text into input:
search.component.html
<ng-content select="[myInput]"></ng-content>
<button type="button" [disabled]="!searchText">Search</button>
I try to subscribe on changes of directive inside of component, but it does not work.
search.component.ts
@Component({
selector: 'my-search',
templateUrl: './search.component.html'
})
export class SearchComponent implements AfterContentInit {
@ContentChild(InputDirective) input: InputDirective;
ngAfterContentInit() {
this.input.changes.subscribe(changes => console.log(changes));
}
}
Also I try to export native input in property element
.
input.directive.ts
@Directive({
selector: '[myInput]'
})
export class InputDirective {
element: HTMLInputElement;
constructor(private elementRef: ElementRef) {
this.element = this.elementRef.nativeElement;
}
}
And when try to get value of input with getter, but it does not work too.
search.component.ts
@Component({
selector: 'my-search',
templateUrl: './search.component.html'
})
export class SearchComponent implements AfterContentInit {
@ContentChild(InputDirective) input: InputDirective;
get searchText(): string {
return this.input.element.value;
}
}
Can anyone help me with this? Here is link for experiments.
set searchText(value: string) { this.input.element.value = value; }
– Yuri Beliakov