K
K
kikosko2018-09-22 17:11:50
Angular
kikosko, 2018-09-22 17:11:50

Why does the Post data update method not work?

When I click the "Edit" button, information about a specific post goes into the input fields, but when I click the "updatePost" button to update this data, the information is updated for all posts except for the one where I want to update the information. Help me solve this problem and understand what I'm doing wrong

Edit component template:

<form [formGroup]="angFormEd" novalidate>
            <div class="form-group">
                <label class="col-md-4">Picture Title</label>
                <input type="text" class="form-control" formControlName="titleEd" minlength="1" #titleEd
                       [(ngModel)]="edData.title"/>
            </div>

            <div class="form-group">
                <label class="col-md-4">Picture Address (url)</label>
                <input type="url" class="form-control" formControlName="urlEd" #urlEd pattern="https?://.+"
                       title="Include http://" [(ngModel)]="edData.url"/>
            </div>
   
            </div>
            <div class="form-group but-group">
                <button (click)="updatePost(titleEd.value, urlEd.value, edData.id); angFormEd.reset(titleEd.value, urlEd.value)"
                      
                        class="btn btn-primary">Update Post
                </button>
            </div>
        </form>
    </div>
</div>


TS of the editing component:
editPost(picId: Picture[]): void {
        this.edData = picId;
    }

    updatePost(title: string, url: string, id:number): void {
        const update: Picture[] = this.collection.map((p)=>{
            p.id  = id;
            p.title = title;
            p.url = url
        });
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-09-22
@kikosko

updatePost(title: string, url: string, id:number): void {
    const update: Picture[] = this.collection.map((p)=>{
        p.id  = id;
        p.title = title;
        p.url = url
    });
}

If the goal is to update the elements of an array, one should use forEach instead of map, and there is no need to get the result. And why are you updating the entire array if, according to you, only one element needs to be updated? Or do you not understand what is happening in this code?
You need to find the desired element by id and update only it:
UPD. Another weird moment. According to your code, the edData property is an array:
editPost(picId: Picture[]): void {
    this.edData = picId;
}

And if you look at the template - it is assumed that this is an object:
Where does edData get its id from if it's an array?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question