Reputation: 2512
I've viewed quite a few solutions on stackoverflow with no success. Just to add as reference, I've viewed the following solutions:
Explanation of the component:
I have a list of names shown. Each name, you can click on and an input field will show. If you lose focus of the input field, it should "save" any changes to the name made in the input field.
There is a button and input field below for adding new people to the list as well.
So I have a dynamic list of names, that should be editable.
Current Behavior:
When clicking on a name, the input field shows. I added "autofocus" to the input field. But when the input field does show, focus is not set on the input field.
When clicking again into the input field, I gain focus. So basically I never had focus to begin with..
Behavior I want:
When clicking on a name, the input field should show. Focus should be in the input field. So right away I can edit the name after clicking it. If I click outside of the input field, I should lose focus.
Here is an example plunker. Included in the code is a copy-paste of a solution given from one of the stackoverflow answers I linked at the beginning of my post. My code is in app/app.component.ts
starting from where I wrote: // begin my code:
https://plnkr.co/edit/pFMUsNuVqalnv2lR0nQC?p=preview
To comply with stackoverflow rules, I need to add code with a plunker link. Below is a copy-paste of my component from the plunker (WITHOUT the directive):
import {Component} from '@angular/core';
interface Person {
name: string
}
@Component({
selector: 'sample-app',
template: `
<div *ngFor="let person of listOfPeople">
<span *ngIf="personOnEdit !== person" (click)="edit(person)">{{ person.name }}</span>
<input *ngIf="personOnEdit === person"
[(ngModel)]="person.name"
autofocus
(focusout)="edit(null)" />
</div>
<br/>
<div>
<form (submit)="addPerson()">
<input placeholder="New Person Name" #newPersonName />
<button (click)="addPerson(newPersonName.value); newPersonName.value = ''">Add Person</button>
</form>
</div>
`
})
export class AppComponent {
personOnEdit: Person = null;
listOfPeople: Array<Person> = [
{
name: "Bob",
},
{
name: "Catie",
},
{
name: "Dan",
}
];
edit(person) {
this.personOnEdit = person;
}
addPerson(personName) {
this.listOfPeople.push({ name: personName })
}
}
Any help is appreciated. If you need any clarifications, please post. Sorry if my response is slow, it is quite late for me and I need to wake up early tomorrow :) Thank you
Upvotes: 0
Views: 2247
Reputation: 57919
a directive like
@Directive({
selector: "[autofocus]"
})
export class AutoFocusDirective {
constructor(public elementRef: ElementRef) {}
ngOnInit() {
setTimeout(() => {
this.elementRef.nativeElement.focus();
});
}
}
In a
<div *ngFor="let item of items">
<input autofocus>
</div>
<button (click)="items.push(1)">add</button>
See stackblitz Must be work
Upvotes: 2