Nope
Nope

Reputation: 51

How can I use Selectize.js with Angular2?

I'm trying to implement Selectize.js with Angular2 but I can't seem to make it work. Here's what I've tried in the HTML component:

  <div class="form-group">
    <label for="friends">Friends</label>
    <input type="text" class="form-control" #friends
            [(ngModel)]="user.friends" name="friends"
            #picture="ngModel">
  </div>

And the in the component:

declare let $: any;

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  providers: [ AuthenticationService, UserService, MessageService ]
})
export class ProfileComponent implements OnInit, AfterViewInit  {
  @ViewChild('friends') el:ElementRef;

  constructor(
    private _userService: UserService,
    private _authService: AuthenticationService,
  ) { }

  ngAfterViewInit() {

    $('#friends').selectize({
      delimiter: ',',
      persist: false,
      create: function(input) {
        return {
          value: input,
          text: input
        }
      }
    });
  }

  ngOnInit() {

    //...
  }

  onSubmit(event) {
    //...
  }

}

So what I'm trying to do is simply implement Selectize in the friends input. I want the user to be able to write the names of his friends and then recuperate them in Angular with an array of names.

But nothing happens in the interface, Selectize doesn't do anything. How come?

Upvotes: 3

Views: 5174

Answers (4)

Satish Pokala
Satish Pokala

Reputation: 304

I am using this https://www.npmjs.com/package/ng-selectize

And it works perfectly in my angular 5 project

Upvotes: 0

GBrooksy
GBrooksy

Reputation: 373

To get selectize.js to work with (Angular 8 tested) without the ng2-selectize plugins (extra weight) you can do the following:

Install the plugin via NPM:

npm i selectize

Then install the types so you can get access to intellisense and also remove any undeclared methods that typescript doesn't understand that's associated with selectize.

npm i @types/selectize

Now in your component you need to import the plugin, do so with the following: (make sure your path to node_modules is correct in your app from your component)

import 'node_modules/selectize/dist/js/standalone/selectize.js';

You'll need jQuery if you haven't imported/installed this already. Now in your component use the AfterViewInit() method - if loading upon first initialisation of the page so you know the DOM has been created. Like so:

    ngAfterViewInit() {
      $(<selector>).selectize({<options-object>});
}

Then similar to what Rob is suggesting, utilise one of the following methods that selectize offers: documentation here

onChange: (value) => {}, onItemAdd: (value, $item) => {}

This should get you up and running with the plugin, you'll need to import the CSS themes or use your own styling.

Upvotes: 0

NicholasAzar
NicholasAzar

Reputation: 31

To hopefully make this a bit easier I've created the ng2-selectize component available on github & npm.

Its usage could be:

export class MultiSelectExampleComponent {
  options = [{
		label: 'Angular 2',
		value: 'angular2'
	}, {
		label: 'ReactJS',
		value: 'reactjs'
	}
  ];
  config = {
    labelField: 'label',
    valueField: 'value',
    highlight: false,
    create:false,
    persist:true,
    plugins: ['dropdown_direction', 'remove_button'],
    dropdownDirection: 'down',
    maxItems: 5
  };
  placeholder: string = 'Placeholder...';
  value:string[];

  onValueChange($event) {
    console.log("Option changed: ", $event);
  }
}
  
<div class="example">
    <ng2-selectize [config]="config" [options]="options" [placeholder]="placeholder" [(ngModel)]="value" (ngModelChange)="onValueChange($event)"></ng2-selectize>
</div>

Upvotes: 3

Rob
Rob

Reputation: 115

Two way data binding to selectize doesn't work in angular2, so get rid of those ngModels. Instead, this is what I do is implement the onItemAdd and onItemRemove functions in selectize, like so:

activateSelectize() {
    var $selecitize= jQuery('.selectize');

    this.select= $selectize.selectize({
        delimiter: ',',
        create: (input) => {
            return {
                value: input,
                text: input
            };
        },
        onItemAdd: (value) => {
            this.updateValue({selected: value});
        },
        onItemRemove: (value) => {
            this.updateValue({deselected: value});
        },
    });
 }

And this is the html:

<select class="selectize">
        <option *ngFor="let option of options" value="{{option[0]}}">{{option[1]}}</option>
</select>

Upvotes: 0

Related Questions