0
votes

I was trying to select the first node of the Angular PrimeNG tree component, but the only thing I manage to do is to select the root node, but that doesn't trigger the click event of it.

I am trying to find a way of how to trigger the click event on the first node when the data has been loaded on the component.

ngAfterViewInit() {
        setTimeout(() => {
            this.node = this.files[0].expanded = true;
            this.node = this.files[0];
        }, 2000);
    }

tree is populated with JSON data fetched from an endpoint via a promise in a service like the example here https://www.primefaces.org/primeng/v7.2.6-lts/#/tree :

@Injectable()
export class NodeService {

    constructor(private http: Http) {}

    getFiles() {
        return this.http.get('showcase/resources/data/files.json')
                    .toPromise()
                    .then(res => <TreeNode[]> res.json().data);
    }
}

How can I figure out when the data finished loading on that and then select the first node?

I forked an example on stackblitz, with the only difference that it's using an observable instead of promise to populate the data: https://stackblitz.com/edit/angular-primeng-tree-sml-9swyq6?file=src/app/app.component.ts

On this example, I've enabled the loading=true.

So how can I found out when the loading is finished, switch the loading to false and select and trigger click on the first node of the tree?

1
Can you share some code please? - Antikhippe
I've updated the descript, I cannot describe it more simple than that. - wilbi
How do you populate the p-tree? - Antikhippe
I got a service with a promise fetching the data from the endpoint. Excactly like the example with the promise here: primefaces.org/primeng/v7.2.6-lts/#/tree this.nodeService.getFiles().then(files => this.files = files); How would you do it in their example to trigger a click on the first node? - wilbi
I've added a similar example on StackBlitz and updated the description of the question again. - wilbi

1 Answers

1
votes

You should expand first node in the return of your promise, not in the ngAfterViewInit method because data might not be available at that moment.

Try something like that:

this.nodeService.getFiles().then(files => {
  this.files1 = files;
  this.files1[0].expanded = true;
  this.loading = false;
});

See demo