Best way to send event from AngularJS parent component to Angular 7 child component? (ngUpgrade) - angular-upgrade

I have an AngularJS (1.7) app which is being migrated to Angular 7, using ngUpgrade. So the AngularJS and Angular frameworks are running at the same time, new components are written in Angular, and sometimes these modern Angular components are used inside of legacy AngularJS components.
In my case, the parent component needs to communicate with the child component in certain circumstances.
The ngUpgrade docs clearly show how to pass data and propagate events from the child Angular component to the parent AngularJS component:
<legacy-angularjs-component>
<div>{{ $legacyCtrl.whatever }}</div>
<modern-angular-child-component
[data]="$ctrl.initialDataForChildComponent"
(changed)="$ctrl.onChildComponentChanged($event)"
>
</modern-angular-child-component>
</legacy-angularjs-component>
To make that work, you just need to add a couple properties to the Angular child component: #Input() data; for the initial data, and #Output() changed = new EventEmitter<WhateverThing>(); that can then be used to propagate events to the parent component by doing this.changed.emit(this.whateverThing).
That all works, but what about propagating events from the parent to the child? I know how to do this in Angular, e.g. with #ViewChild or using observables, but those mechanisms are not available in my app's AngularJS environment. So the parent component cannot use them.
Two approaches I have tried that do work are:
Creating a separate service, which both components share.
Pass a reference to the parent controller into the child controller like this:
<legacy-angularjs-component>
<div>{{ $legacyCtrl.whatever }}</div>
<modern-angular-child-component
[observe]="$ctrl.registerObserver",
>
</modern-angular-child-component>
</legacy-angularjs-component>
...and then having the child component invoke this observe function:
ngOnInit() {
if (this.observe) {
// Pass reference to child component to the
// parent, so parent can directly send it messages.
this.observe(this);
}
}
This way, the parent has a direct reference to the child once the components are set up. The child implements some TypeScript interface that defines all the methods of the child that the parent can invoke to inform the child of events.
Both of those do work, but they both strike me as fairly kludgey and a lot of rigamarole to have to do for something as simple as sending an event to a child component.
Since this is easy to do in both AngularJS and Angular, I wondered if I might be missing an easier/simpler way to do the same thing in the context of ngUpgrade, where the parent is AngularJS and the child is Angular 7.
Or is my second approach a reasonable way to do it?

Well, as Eazy-E once said, "Ask, and ye shall immediately think of a simpler answer, right after you post the question in public."
A better solution than either of my first two mentioned above is to simply use regular Angular one-way bindings and use the OnChanges mechanism provided by Angular.
<legacy-angularjs-component>
<div>{{ $legacyCtrl.whatever }}</div>
<modern-angular-child-component
[observed]="$ctrl.valueThatChildIsObserving"
>
</modern-angular-child-component>
</legacy-angularjs-component>
Then, in the child component:
import { Component, Input, OnChanges, SimpleChanges } from '#angular/core';
export class MyChildCompoennt implements OnChanges {
#Input() observed: SomeWhateverObject;
ngOnChanges(changes: SimpleChanges) {
console.log(changes);
// Inspect changes (it contains old and new values
// for `observed` object. That object could be a string
// or something more complicated with multiple properties.\
}
}
This way, when the parent component wants to tell the child to do something, it can just do this.valueThatChildIsObserving = someWhatever;.
Angular will handle invoking the child componentngOnChanges(), passing it a structure containing the old and new value of the property.
You have to implement the child component so that it can inspect the changed value and execute the correct action, but that is pretty simple and avoids having to have the parent/child share references to each other.
I think this is a reasonably simple way to implement "propagate some kind of event from parent component to child component" in a hybrid AngularJS/Angular app using ngUpgrade.

Related

How to detect svelte component from DOM?

Currently making an google chrome extension to visualize svelte components, this would only be used only development mode. Currently I am grabbing all svelte components by using const svelteComponets = document.querySelectorAll(`[class^="svelte"]`); on my content scripts but it is grabbing every svelte element. What are some approaches to grab only the components?
Well you mostly can't get to the Svelte component from the DOM elements.
The reason, appart from Svelte won't give you / expose what's needed, is that there isn't a reliable link between components and elements.
A component can have no elements:
<slot />
Or "maybe no elements":
{#if false}<div />{/if}
It can also have multiple root elements:
<div> A </div>
<div> B </div>
<div> C </div>
By bending the cssHash compiler option a lot, you would probably be able to extract the component "name", maybe class name from the CSS scoping classes generated by Svelte. (Which, in turn could break CSS-only HMR updates with Vite, but that's another story.)
But from there, you won't be able to reliably get to the individual component instances... If we keep the component from the last example, once you've grabbed those 6 divs:
<div> A </div>
<div> B </div>
<div> C </div>
<div> A </div>
<div> B </div>
<div> C </div>
... how do you know where one component instance ends and where the other begins? Or even that there are two components?
I believe, the most reliable way to achieve what you want is probably to use internal Svelte APIs, including those that are used by the actual Svelte dev tools that you want to mimic. (Gotta love when private APIs are the "most reliable"!)
Necessary disclaimer: this only seems reasonable to do this in your case because it is a study subject, and because it's dev only. It would certainly not be wise to rely on this for something important. Private / internal APIs can change with any release without any notice.
If you go in the Svelte REPL and look at the generated JS after enabling the "dev" option, you'll see that the compiler adds some events that are provided for the dev tools.
By trials and experimentation, you can get a sense of how Svelte works, and what dev events are available. You'd also probably need to dig the sources of the compiler itself to understand what's happening with some functions... Being comfortable with a good debugger can help a lot!
For your intended usage, that is build a representation of the Svelte component tree, you'll need to know when a component instance is created, what is its parent component, and when it is destroyed. To add it to the tree, in the right place, and remove it when it goes away. With that you should be able to maintain a representation of the component tree for yourself.
You can know when a component is created with the "SvelteRegisterComponent" dev event (squared in red in the above screenshot). You can know the parent component of a component being instantiated by abusing { current_component } from 'svelte/internal'. And you can know when a component is destroyed by abusing the component's this.$$.on_destroy callbacks (which seems like the most fragile part of our plan).
Going into much more detail about how to proceed with this seems of bit out of scope for this question, but the following basic example should give you some ideas of how you can proceed. See it in action in this REPL.
Here's some code that watches Svelte dev events to maintain a component tree, and exposes it as a Svelte store for easy consumption by others. This code would need to run before your first Svelte component is created (or before the components you want to catch are created...).
import { current_component } from 'svelte/internal';
import { writable } from 'svelte/store';
const nodes = new Map();
const root = { children: [] };
// root components created with `new Component(...)` won't have
// a parent, so we'll put them in the root node's children
nodes.set(undefined, root);
const tree = writable(root);
// notify the store that its value has changed, even
// if it's only a mutation of the same object
const notify = () => {
tree.set(root);
};
document.addEventListener('SvelteRegisterComponent', e => {
// current_component is the component being initialized; at the time
// our event is called, it has already been reverted from the component
// that triggered the event to its parent component
const parentComponent = current_component;
// inspect the event's detail to see what more
// fun you could squizze out of it
const { component, tagName } = e.detail;
let node = nodes.get(component);
if (!node) {
node = { children: [] };
nodes.set(component, node);
}
Object.assign(node, e.detail);
// children creation is completed before their parent component creation
// is completed (necessarilly, since the parent needs to create all its
// children to complete itself); that means that the dev event we're using
// is fired first for children... and so we may have to add a node for the
// parent from the (first created) child
let parent = nodes.get(parentComponent);
if (!parent) {
parent = { children: [] };
nodes.set(parentComponent, parent);
}
parent.children.push(node);
// we're done mutating our tree, let the world know
notify();
// abusing a little bit more of Svelte private API, to know when
// our component will be destroyed / removed from the tree...
component.$$.on_destroy.push(() => {
const index = parent.children.indexOf(node);
if (index >= 0) {
parent.children.splice(index, 1);
notify();
}
});
});
// export the tree as a read only store
export default { subscribe: tree.subscribe }

Aurelia - Accessing ViewModel functions/binding from within Generated DOM elements

I have a section of my view (html) that is generated programmatically by a viewmodel/class. This uses the Aurelia DOM (Aurelia Docs - pal :: Dom) functionality to generate and add the raw HTML elements to the view.
However, I am unable to get events within the generated html to call back to the viewmodel. An example:
let deleteButton = this.dom.createElement("button");
deleteButton.setAttribute("onclick", "cancelCreditNote(`${ row.creditNoteId }`)");
A click on the generated button won't call back to the viewmodel, which does have a cancelCreditNote function. Various other things like deleteButton.setAttribute("click.delegate", "cancelCreditNote('${ row.creditNoteId }')"); do not work either.
Does anyone know how to access a viewmodel class from essentiall 'raw' html in aurelia?
Unfortunately in this instance I cannot use the standard aurelia templating to generate the HTML.
The DOM property on PAL is just an abstraction for the browser's DOM object, create element is likely just calling document.createElement which doesn't afford any Aurelia binding to the created element.
You could try using aurelia.enhance(context, element) which takes an existing DOM element and runs it through the templating engine.
With this method you can also pass a binding context to apply to the element.
In my HTML I use this:
<div id="collapsesidebar" click.delegate="toggleSidebar()">
In my view-model I have this method:
toggleSidebar(){
alert('hi');
}
You could also do this from your view-model with JQuery like this:
attached() {
$('main').on('click', ()=> alert('hi'));
}
The last option is ONLY available áfter the attached() method is triggered: before that the binding needs to do its job and only after that the elements are located inside of the dom.
In other words: this will not work:
activate(){
$('main').on('click', ()=> alert('hi'));
}
because the constructor and the activate method both get fired before the attached method.

Angular2 model-based parent/children form

I'm a newbie with Angular2 (beta1) and I'd like to implement a sort of simple editable grid, built of 2 components. Here I use two fake-data components to keep things simple. They are (see this Plunker: http://plnkr.co/edit/5cZfLTIlhLc82wWV4PQI):
the parent component, named contact. Say it represents a contact with a name.
the child component, named entry. Say it represents an entry for a contact, where each contact can include 0 or more entries. Each entry has an address and a zip code.
I'd like to create a form where the user can edit the contact's properties, and also its children entries: he could add a new entry, delete an existing entry, or edit an existing entry.
To this end, the views for both these components provide a form-based template.
I can think of this data flow:
contact: the user edits the form and then clicks a submit button to save
the whole thing. Thus, I can just have some code handling the submit button
and emitting an event as the component output. The contact has an entries
array property: I can thus use an ngFor directive in its template to render
an entry component for each of them.
entry: the entry has properties addressCtl and zipCtl which represent
the control directives included in the ControlGroup representing the whole
form. Also, I need a couple of properties to be bound as the input of the
component (address and zip), so that in the parent template I can do something like:
<tr *ngFor="#e of entries">
<td><my-entry [address]="e.address" [zip]="e.zip"></my-entry></td>
</tr>
Now, it's not clear to me how to shape the relation between the "model" properties representing the control's input, and the "form" directives properties. I should be able to get the address and zip values from the parent component through the [...] binding, and pass the updated values up through an event fired by the child component (e.g. blur?). Does this make sense in the NG2 world? Anyway, I'm missing a piece here: how can I connect the form controls values to the model properties values? Could anyone make this clearer or point to some good docs?
In fact, using the [...] binding only corresponds to a one-way binding. When the parent property is updated in the parent component, the value is also updated in the child component.
But if you want to update parent attributes from the child, you need to leverage events and #Ouput attribute.
Here is a sample with a labels component:
export class LabelsComponent implements OnInit {
#Input()
labels:string[];
#Output()
labelsChange: EventEmitter;
(...)
removeLabel(label:string) {
var index = this.labels.indexOf(label, 0);
if (index != undefined) {
this.labels.splice(index, 1);
this.labelsChange.emit(this.labels);
}
}
addLabel(label:string) {
this.labels.push(this.labelToAdd);
this.labelsChange.emit(this.labels);
this.labelToAdd = '';
this.addAreaDisplayed = false;
}
}
This way you can leverage two way binding on this component:
<labels [(labels)]="company.labels"></labels>
Hope it answers your question,
Thierry
Just moved the comment to answer...
You can pass the object e, instead of passing string.
i.e
<my-entry [entry] = "e"></my-entry>
then in your my-entry component, use ng-model for each input. so you automatically gets 2 way bindings.

querySelect angular component as MyComponent

I have an angular component
<my-component foo="" bar=""></my-component>
And its corresponding class MyComponent
I use this component in my html
<my-component foo="bar" bar="foo"></my-component>
<my-component foo="baz" bar="qux"></my-component>
<my-component foo="bar" bar="baz"></my-component>
Now i want to querySelect my custom elements and access their attributes directly. I think about something like this:
List<MyComponent> mys = querySelector('my-component');
mys.forEach((my){
print(my.foo);
my.bar = '1234';
});
There are a view problems with that code:
querySelector always returns Element not MyComponent. can i cast Element to MyComponent?
Is MyComponent to <my-component> like DivElement to <div>?
querySelector cannot select custom elements. i could ad a class to every my-component and select it with that class. or is there another way?
I only can access the attributes with my.getAttribute() not with my.foo. I know, this is because my is still a Element not a MyComponent.
This is not officially supported. There was something like ng-element that allowed this as far as I remember but was intended to be only used for unit tests. There were some changes in the last versions but I don't know the current state.
You should pass references using dependency injection, Angular events (explained here How to communicate between Angular DART controllers) or the scope to access other elements.

Durandal - dispose of viewmodel after completion of registration process

Just wondering if anyone knows a good/simple approach using Durandal to disposing of or re-initializing a viewmodel once it becomes invalid?
I have a registration form that I could 're-initialize' manually after a user has completed the form and registered successfully, but I'd prefer to just dispose of it so that Durandal creates a new registraion view/view model when that particular route is accessed again.
If your viewmodel module returns a function rather than an object, it will create a new one each time rather than reusing the 'singleton' object. See the Module Values section of Creating a Module.
Updated link for the Durandal Module constructor function information: Module Values
You can split the difference:
var cache;
var ctor = function () {
if (cache) return cache;
// init logic
cache = this;
}
Just replace the if(cache) check with whatever "do I need a new thing or not" logic you like.
If you're using routing, simply redirect the user to an instance-based module (one that returns a constructor function). The user will most likely click or touch a button that signifies that he is done with the registration form. That would be the redirect action.
If you're using composition, you would still create an instance-based module. Then, you would use dynamic composition to swap it in once the user signified he was done with the registration form.
Dynamic composition is where the view and/or model attributes on a Durandal composition are, themselves, observables, referencing something like the following in the viewModel:
this.currentView = ko.observable('');
this.currentModel = ko.observable('');
Then, in your HTML:
<div>
<div data-bind="compose: {view: currentView(), model: currentModel())"></div>
</div>
When the user clicks "Done", or something to that effect, functions on your viewModel might look something like:
ctor.prototype.done = function () {
this.setCurrentView('viewmodels/registrationForm.html');
this.setCurrentModel('viewmodels/registrationForm.js');
}
ctor.prototype.setCurrentView = function (view) {
this.currentView(view);
}
ctor.prototype.setCurrentModel = function (model) {
this.currentModel(model);
}
Either one of the approaches above will create the registrationForm only when it's needed.
With Durandal 2.0, you can use the deactivate callback within the composition lifecycle. Here is some documentation http://durandaljs.com/documentation/Hooking-Lifecycle-Callbacks