Angular2 ngOnChanges clone #Input array - arrays

I'm using a DashboardComponent that gets the data from my DashboardService. This Component then passes my array of objects to my form component.
(Plunkr link at bottom of post)
DashboardComponent.ts
private bottleArray: Bottle[] = [];
ngOnInit() {
// Get bottle types from service to the form needing them
this.dashboardService.getBottleTypesAndNames()
.subscribe(bottlesData => {
bottlesData.forEach(bottle => {
// Convert to Bottle type
let bottleObject: Bottle = new Bottle(bottle.bottleTypeId, bottle.bottleName);
this.bottleArray.push(bottleObject);
});
});
}
DashboardComponent.html
<ct-create-order-form [bottleArray]="bottleArray"> </ct-create-order-form>
I did it that way so that my form components linked to my Dashboard won't be doing any call to my service.
I'm trying to clone my #Input so that my data updated from the form is not linked to my parent component (Dashboard), but I can't seem to do it... See code below :
CreateOrderFormComponent.ts
export class CreateOrderFormComponent implements OnChanges {
#Input() private bottleArray: Bottle[];
constructor() { }
private clonedBottleArray: BottleCommand[];
ngOnChanges(changes) {
if (changes.bottleArray) {
let test: BottleCommand[] = changes.bottleArray.currentValue;
// Cloning
console.log(test); // Array of 6 Bottles
this.clonedBottleArray = [...test];
console.log(this.clonedBottleArray); // Empty Array
this.clonedBottleArray = Array.from(test);
console.log(this.clonedBottleArray); // Empty Array
this.clonedBottleArray = test.slice();
console.log(this.clonedBottleArray); // Empty Array
this.clonedBottleArray = test;
console.log(this.clonedBottleArray); // Array of 6 bottles
}
}
Is there any way to achieve what I am doing ? I don't understand why I can't clone my Input when I get the data ?
From this Youtube video made by AngularConnect, he is doing the exact same except that he is manipulating an Object, and I'm manipulating an Array of Objets.
https://youtu.be/-nsedZwvl9U?t=12m22s
EDIT : After creating a Plunkr, this seems to be working correctly in there.
https://plnkr.co/edit/js1vl0fcgOKtQNqXsWTL?p=preview
EDIT 2 : At the ngOnInit() from my DashboardComponent, if I mock the data, it is cloned correctly in my child component.

Looks like angular OnChange not firing due to it specific way of checking, here's brief explanation from this answer:
During change detection, when Angular checks components' input properties for change, it uses (essentially) === for dirty checking. For arrays, this means the array references (only) are dirty checked. Since the rawLapsData array reference isn't changing, ngOnChanges() will not be called.
And in your example, you're .pushing bottles in bottleArray, so OnChange doesn't fire on the same array reference.
To get the changes, you could use DoCheck:
ngDoCheck() {
console.log(this.bottleArray);
this.clonedBottleArray = [...this.bottleArray].slice(0, 4);
console.log(this.clonedBottleArray);
}
it will fire when you push new values to the bottleArray. Working plunker here.

Related

Angular 2: Change Detection of array inside the object

I have an object as follows which comes through #Input.
#Input() data;
//**
{
"class_a":["John","Harr y"],
"class_b":["Joseph","Phlip","David"],
"class_c":[]
}
**//
I need to detect the changes if data added or removed in class_a or class_b but im only getting change detection if values of objects are string.
Since the keys in my object are dynamic i couldn't iterate the object and create Iterable differs.
Is there anyway to detect changes of array inside the object.
My Implementation:
constructor(private differs: KeyValueDiffers) {
this.keyValueDiffer = differs.find({}).create();
}
ngDoCheck() {
let changes = this.keyValueDiffer.diff(this.data[this.component.factedBindKey]);
if (changes) {
console.log('Changes detected');
}
}
you can test like this
constructor(private cd: ChangeDetectorRef) {
}
ngOnChanges() {
let actualData =this.data
this.mymethod(actualData);
}
and call this line where you want to access that actual data like this
mymethod(data){
this.cd.detach();
//write main logic
}

Observable array is empty in ngrx

I have a an observable array that binds to a data grid in the html and this is working fine. My component.ts gets the array like:
this.data = this.store.pipe(select(selectData));
where selectData is an ngrx action. I'm trying to set the value of an input outside the data grid based on the first value in the data array. I'm trying something like
this.input= this.data.pipe(map(m =>
moment(new Date(m[0].timestamp / 1000000)).format('DD-MM-YYYY HH:mm:ss')));
When I'm debugging this, I can see the break point on the line with moment(new Date... hitting. However, the m at this time is an empty array. Both of the above statements are declared in ngOnInit like
ngOnInit(): void {
this.data = this.store.pipe(select(selectData));
this.input= this.data.pipe(map(m =>
moment(new Date(m[0].timestamp / 1000000)).format('DD-MM-YYYY HH:mm:ss')));
}
It looks like the observable is resolved before the array is actually populated causing the input to be undefined. How can I make sure that the this.data array is actually fully populated by the time I try to set the this.input?
You need to subscribe in order for the selector to pick up data from the store. Make the following change:
ngOnInit(): void {
this.store.pipe(select(selectData))
.subscribe(m => {
this.input = moment(new Date(m[0].timestamp / 1000000))
.format('DD-MM-YYYY HH:mm:ss');
});
}

firing $onChanges hook when collection is updated from the service in angularjs

I am trying to make $onChanges hook work by using immutable way.
Chat Service
class ChatService {
constructor() {
this.collection = {
1: [
{
chat: 'Hi',
},
{
chat: 'Hello',
},
{
chat: 'How are you?',
},
],
};
}
getCollection() {
return this.collection;
}
getChatById(id) {
return this.collection[id];
}
addChat(id, chat) {
// this.collection[id].push(chat);
this.collection[id] = this.collection[id].concat(chat);
}
}
Chat Component
const Chat = {
bindings: {},
template: `<chat-list chats="$ctrl.chats" add-msg="$ctrl.addMsg(chat)"></chat-list>`,
// template: `<chat-list chats="$ctrl.chats[$ctrl.id]" add-msg="$ctrl.addMsg(chat)"></chat-list>`,
controller: class Chat {
constructor(ChatService) {
this.ChatService = ChatService;
this.id = 1;
// if i get the all the chat collection by
// this.chats = ChatService.getCollection()
// and then use like above in the commented out template,
// and it works and triggers $onChanges
this.chats = ChatService.getChatById(this.id);
}
addMsg(msg) {
this.ChatService.addChat(this.id, { chat: msg });
}
},
};
Chat List Component
const ChatList = {
bindings: {
chats: '<',
addMsg: '&',
},
template: `
<div>
<li ng-repeat="chat in $ctrl.chats">{{chat.chat}}</li>
<form ng-submit="$ctrl.addMsg({chat: chatmodel})">
<input ng-model="chatmodel">
</form>
</div>
`,
controller: class ChatList {
$onChanges(changes) {
console.log(changes);
if (changes.chats && !changes.chats.isFirstChange()) {
// this.chats = changes.chats.currentValue;
}
}
},
};
However, $onChanges hook doesn't fire. I know that in order to make the $onChanges fire, need to break the reference of binding chats in chat-list component from the chat component.
Also I could re-fetch the chats after adding on the addMsg method, it would work and trigger $onChanges but if the msg was from the another user and lets say if I was using Pusher service, it would only update the chats collection on the Chat Service not the chat-list component.
One way $onChanges seems to fire is when I get all the chat collection and then use ctrl.id to get particular chats when passing via the bindings like <chat-list chats="$ctrl.chats[$ctrl.id]" instead of <chat-list chats="$ctrl.chats. However, this will update chat list without doing anything on the $onChanges.
Ideally, I would like to update the chat list on the view by <chat-list chats="$ctrl.chats and then using the currentValue from the $onChanges hook and not use like $watch and $doCheck. I am not sure how to do it. Any help is appreciated. Thanks and in advance.
Here's very basic example of it on the plunkr.
Let's walk trough what your code is doing for a minute to ensure we understand what's going wrong:
The constructor in ChatServices creates a new object in memory (Object A), this object has a property 1 which holds an array in memory (Array 1)
constructor() {
this.collection = {
1: [
{
chat: 'Hi',
},
{
chat: 'Hello',
},
{
chat: 'How are you?',
},
],
};
}
In your component's constructor, you use the ChatService to retrieve Array 1 from memory and store it in the this.chats property from your component
this.chats = ChatService.getChatById(this.id);
So currently, we have two variables pointing to the same array (Array 1) in memory: The chats property on your component and the collection's 1 property in the ChatService.
However, when you add a message to the ChatService, you are using the following:
addChat(id, chat) {
this.collection[id] = this.collection[id].concat(chat);
}
What this is doing is: It updates collection's 1 property to not point towards Array 1, but instead creates a new array by concatenating both the current Array 1 and a new message, store it in memory (Array 2) and assign it to collection[id].
Note: This means the Object A object's 1 property also points to Array 2
Even tho the collection's 1 property has been updated properly when it comes to immutability, the chats property on your component is still pointing towards Array 1 in memory.
There's nothing indicating it should be pointing to Array 2.
Here's a simple example demonstrating what's happening:
const obj = { 1: ['a'] };
function get() {
return obj['1'];
}
function update() {
obj['1'] = obj['1'].concat('b');
}
const result = get();
console.log('result before update', result );
console.log('obj before update', obj['1']);
update();
console.log('result after update', result );
console.log('obj after update', obj['1']);
As you can see in the above snippet, pointing obj['1'] towards a new array doesn't change the array result points to.
This is also why the following is working correctly:
One way $onChanges seems to fire is when I get all the chat collection
and then use ctrl.id to get particular chats when passing via the
bindings like <chat-list chats="$ctrl.chats[$ctrl.id]" instead of
<chat-list chats="$ctrl.chats.
In this case you are storing a reference to Object A. As mentioned above, the 1 property on the ChatService's collection is updated correctly, so this will reflect in your component as it's also using that same Object A.
To resolve this without using the above way (which is, passing Object A to your component), you should ensure the component is aware of the changes made to Object A (as it can not know this when not having access to it).
A typical way these kind of things are done in Angular (I know this is AngularJS, but just pointing out how you can resolve this in a way Angular would do and works fine with Angular JS) is by using RXjs and subscribe to the chats changes in your component.

Is it possible to make ng-repeat delay a bit redrawing of array content

I'm using ng-repeat to (guess) put array content in table.
Content is drawn dynamically, and it works well, when I'm modifying single elements of an array. But when I reload a whole array, there is this moment, when array is reassigned with new value, and ng-repeat draws blank table (which is actually logically correct). Is there a way to delay redrawing of content that way, the ng-repeat ignores the moment when the array is empty? Like the content is switched to new content without the 'clear' time.
I'm assigning new elements to array this way:
items = newItems;
where items is the array ng-repeat uses and newItems is an array of items freshly downloaded from database. The newItems is complete, when the assignment occurres. I'm not doing items = []; before the assignemt.
I'm usign angular 1.3
EDIT:
the ng-repeat:
<tr ng-repeat="order in submittedOrders">
stuff
<\tr>
js:
`$scope.reloadView = function() {
$scope.submittedOrders = OrdersService.getOrdersByStatus(ORDER_STATUS.submitted);
};`
Can it be the that the table is cleared in the first place, before call to database(service takes data from database) and during the wait, the table is cleared?
You may have to make use of Observables and async pipe of Angular.
Here are few steps you can take:
Convert your newItems to a rxjs Subject.
newItems$ = new Subject();
Whenever you get new values for your array, emit them via subject.
this.newItems$.next(newItems);
Make the items an observable of newItems$, and filter out empty arrays.
items = this.newItems$.pipe(
filter((a:any[]) => {
return a.length != 0;
})
);
In your template, use async pipe to iterate over array.
*ngFor="item of items | async"
Below is relevant parts of code that can get you started.
import { Observable, of, from, Subject } from 'rxjs';
import { filter, mapTo } from 'rxjs/operators';
...
newItems$ = new Subject();
items = this.newItems$.pipe(
filter((a:any[]) => {
return a.length != 0;
})
);
...
// A test method - link it to (click) handler of any div/button in your template
// This method will emit a non-empty array first, then, after 1 second emit an empty
// array, and then, after 2 seconds it will emit a non-empty array again with updated
// values.
testMethod() {
this.newItems$.next([3,4,5]);
setTimeout((v) => {
console.log("Emptying the array - should not be displayed browser");
this.newItems$.next([]);
}, 1000);
setTimeout((v) => {
console.log("Updating the array - should be displayed in browser");
this.newItems$.next([3,4,4,5]);
}, 2000);
}

Array as Model for Service Breaks when Empty

I have two routes: one has a custom component that repeats the data in an array and allows the user to add and remove items, the other route only displays the model. The model is stored in a service. The model JSON data looks like this:
[
{name: "one"},
{name: "two"},
{name: "three"}
]
The components are all using ng-model and assigning this to a variable vm. Following all the best practices from John Papa style guide.
If I empty the array either by using slice(), pop(), or setting the array length to 0, it breaks. You can still add data to it, but if you navigate to the other route, the model will show as an empty array. And if you navigate back again, the array is still empty.
If I make my model an object with a key and the array as the value, everything works as expected. So my question is, is this just a limitation or am I doing something wrong?
{
myarray: [
{name: "one"},
{name: "two"},
{name: "three"}
]
}
Here is the working example using the object containing the array.
And here is the non working example just using the array.
You'll see on the one that does not work, you'll empty the array and then add to it, it will not persist data across the routes.
you'll empty the array and then add to it, it will not persist data across the routes
1st Problem: in getAsync() method.
When your model is empty you call callAtInterval() every 100 milliseconds and you never resolve your promise (infinite loop).
function getAsync() {
function callAtInterval() {
if (!_.isEmpty(genericHttpModel.model)){
$interval.cancel(promise);
deferred.resolve(get());
}
}
var deferred = $q.defer();
var promise = $interval(callAtInterval, 100);
return deferred.promise;
}
Therefore when user goes to home (root) route:
genericHttpService.getAsync().then(function(model){
vm.model = model; // <-- never called
});
So remove if (!_.isEmpty(genericHttpModel.model)) statement
function callAtInterval() {
$interval.cancel(promise);
deferred.resolve(get());
}
}
2nd problem: in add method:
function add() {
if (modelEmpty()) {
initModelAndAddOne();
} else {
vm.model.push({});
}
}
In initModelAndAddOne you reset original instance of vm.model with:
vm.model = [];
Your model is already empty, why to redefine it with =[], make it simple:
function add() {
vm.model.push({});
}
Working Example Plunker
working example using the object containing the array.
So why it works:
1st off _.isEmpty(genericHttpModel.model) will always return false because object contains field names a.e: genericHttpModel.model = {names:[]}
2nd - vm.model = [] resets names field only and not service object

Resources