0

I imported jquery query builder in my project as How to use Jquery Query Builder in Angular told.

ngOnInit() {
this.templateService.getTags(this.contentType)
  .then(tags => {
    this.tags = tags;
  });
}

ngAfterViewInit() {
  this.getQueryBuilder();
}

getQueryBuilder() {
let self = this;
if (self.builder) {
  $(self.builder.nativeElement).queryBuilder({
      plugins: ['bt-tooltip-errors','not-group'],

      filters: [{
          id: 'tag',
          label: 'Tag',
          type: 'string',
          input: 'select',
          values: {
                1: 'Books',
                2: 'Movies',
                3: 'Music',
                4: 'Tools',
                5: 'Goodies',
                6: 'Clothes'
            },
          operators: ['equal']
      }],

      rules: this.rules_basic
  });

}
}

Although it worked, angular lifecycle hooks are not working. It always comes to the getQueryBuilder() function first,usually ngOnInit() executes first,and then gAfterViewInit(),and the autocompletion is not working.Why? Can somebody help me? Thanks a lot.

Hal Shaw
  • 25
  • 6
  • have you informed the class that it will be implementing ``AfterViewInit`` ? – CruelEngine Nov 02 '17 at 09:05
  • Informed the class? I don't quite understand that.I need to use a variable in getQueryBuilder() which came from a service when ngOnInit() executed,but it came directly to the getQueryBuilder() function and then executed ngOnInit() when I debuged it. I don't know why. – Hal Shaw Nov 02 '17 at 09:24
  • ``ngOnInit()`` will get executed and later ``ngAfterViewInit()`` will get executed . ``ngOnInit()`` won't wait for service response as it is async. So to use the variable inside your ``getQueryBuilder() `` , you'll have to call ``getQueryBuilder() `` after getting the response – CruelEngine Nov 02 '17 at 11:11
  • I tried that,but it's still not working.This is kind of weird.I also tried to put both `getQueryBuilder()` and the variable into `ngOnInit()`,it still came to `getQueryBuilder()` first, and then the variable from service. – Hal Shaw Nov 03 '17 at 01:30
  • can you post how you've subscribed to service in ngOnInit() ? – CruelEngine Nov 03 '17 at 05:00
  • Just like the code above,it gets the tags variable from the templateService. – Hal Shaw Nov 03 '17 at 06:06

1 Answers1

0

try this :

ngOnInit(){
this.templateService.getTags(this.contentType)
  .then(tags => {
    this.tags = tags;
    this.getQueryBuilder();
  });
}

Now only after the response from templateService , this.getQueryBuilder() is executed

CruelEngine
  • 2,701
  • 4
  • 23
  • 44