7.9: Setting Main Photo in Angular
Adding setMainPhoto() Service Method
In user.service.ts
, add a new method called setMainPhoto()
:
Adding setMainPhoto() Method to PhotoEditorComponent
In photo-editor.component.ts
add a method to use the service above:
Use the Method in the Template
Next, we'll use our new methods in the photo-editor.component.html
template:
We added a few things here.
(click)="setMainPhoto(photo)
- to trigger our method on a click event[ngClass]="photo.isMain ? 'btn-secondary active' : 'btn-default'"
- to toggle classes based on whether or not a photo is the main photo.[disabled]="photo.isMain"
- to disable the button if the photo is already the main photo.
Our button should "work" now. However, if a user clicks the Main button - it won't be immediately reflected in the app. A user will have to reload the page to see the changes. This isn't ideal. We'll fix this next.
Dynamically Updating Main Photo
We need to do something similar to what we're already doing in our API on our frontend to update the photo array without having to refresh the page.
We'll use a JavaScript library called UnderscoreJS to make the array manipulation much more simple. It's probably not a perfect analogy, but Underscore provides similar functionality to LINQ when working with collections.
In photo-editor.component.ts
, make the following changes:
In the setMainPhoto()
method - we're doing the same thing as our API - except we're working with the Photos[]
in our component.
Finding the photo in our photos array that is set to isMain
Setting the photo currently set to main to false
Setting the photo the user clicked on to main.
We're making progress! If we click the Main button - we see our selection being applied on the buttons immediately. However, we're still not seeing the Photo changing in the profile card on the left. This involves passing data from a child component (PhotoEditorComponent) to a parent component (MemberEditComponent) we'll work on that next.
Updating Profile Picture Dynamically
First, let's add an Output
property that is an EventEmitter
to the photo-editor.component.ts
class:
Now, when we call the setMainPhoto()
method, we need to "emit" the photoUrl:
Now, we can use this output property and event emitter in the parent component: MemberEditComponent:
In member-edit.component.html
add this to the <app-photo-editor>
element.
Now we need to implement the updateMainPhoto()
method in our member-edit.component.ts
file:
Test this in your Angular application. Log in as a user with multiple photos and try switching the main photos. The profile picture in the panel on the left should update as well now!
Last updated