Showing posts with label angular. Show all posts
Showing posts with label angular. Show all posts

August 21, 2017

Scroll to item-of-interest in Angular

Imagine you have a list of elements of some kind (by means of *ngFor). You'd like to make that Component aware of the fragment in the URL so it can scroll to the element identified by it.

For instance, you let the user create a new element in a form in one page and you want that on return, the list scrolls automatically to the item just added. You are using Angular routing facilities.

For more background, you can check the discussion on the issue on the Angular project.

There, some users have provided their approaches. On the basis of some solutions suggested there, I've built my own and it seems to work fine:

[...]

private fragment: string;

constructor(private route: ActivatedRoute { }

ngOnInit() {
this.route.fragment.subscribe(fragment => { this.fragment = fragment; });
}

ngAfterViewChecked(): void {
try {
document.querySelector('#' + this.fragment).scrollIntoView();
} catch (e) { }
}

[...]

I think this adds very little bloat and it handles these situations:

  • No fragment present in the route.
  • Fragment present but invalid (querySelector() throws).
  • Fragment present and valid, but the element is not present.

Actually, the try block is masking these situations rather than handling them. Nevertheless, usually you won't find yourself needing to do anything about them.

July 07, 2017

Self-containment challenge in Angular

I didn't plan on writing too much about web development here, but for the past months I've been learning modern web frameworks/techonologies and I've found something worthy writing about regarding Angular.

In Angular, as in other well designed framework you are expected to separate concerns as much as possible. For instance, Components should be as reusable as possible. One feature for such reusability is self-containment. That is, while sometimes you need their host component to interact with them beyond their APIs (Inputs, Outputs, etc.), you need to move in a slightly lower layer for things like adding/removing CSS classes. But you can take measures so everything is under control.

Nonetheless, you can see yourself in trouble with the markup. Due to the rigidity of HTML, certain elements must be direct children of their 'semantic ancestors' if you don't want the browser to make a mess out of your markup. For instance, a <tr> must be a direct child of a <table>, or at least of a <thead>, <tbody> or <tfoot> —among a few others that don't alleviate the issue—. The same holds for lists; for instance an <ul> must contain <li>s.

Let's look at the problem with a concrete example.