Reputation: 2652
I trying to set focus on show:
<div>
<div style="height: 50px; width: 100%" (click)="inEdit=true">
<div *ngIf="!inEdit">
bla
</div>
<mat-form-field *ngIf="inEdit">
<input (blur)="inEdit=false"
autofocus matInput >
</mat-form-field>
</div>
</div>
it is work only on first click.
Upvotes: 2
Views: 613
Reputation: 22213
You can programmatically call a focus method of HTML element whenever you need!
Try this:
Template:
<div>
<button mat-raised-button color="primary" (click)="inEdit=true;focus()">Edit</button>
<div style="height: 50px; width: 100%" (click)="inEdit=true">
<mat-form-field *ngIf="inEdit">
<input #ref matInput >
</mat-form-field>
</div>
</div>
TS:
import {Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'input-overview-example',
styleUrls: ['input-overview-example.css'],
templateUrl: 'input-overview-example.html',
})
export class InputOverviewExample {
@ViewChild("ref",null) refField: ElementRef;
focus(): void {
setTimeout(() => {
this.refField.nativeElement.focus();
}, 100);
}
}
Upvotes: 3
Reputation: 11
We can achieve all DOM related operations in Angular using @ViewChild decorator whic comes from angular core.
Related Template
HTML :
<input type="text" #inputName>
Component :
import { Component,AfterViewInit,ViewChild ElementRef} from '@angular/core';
...
@ViewChild('inputName') inputEl:ElementRef;
ngAfterViewInit() {
setTimeout(() => this.inputEl.nativeElement.focus());
}
Using this ElementRef we can do dynamic DOM(Component) Rendering.
Make sure before going to use ElememntRef,All DOM is rendered in local browser
Upvotes: 0