Use trait to modify component class
Question
Hi!
I'm trying to change the value of the classes with very little succes.
Here is my custom trait's onValueChange function:
onValueChange() {
var traitModel = this.model;
var selectedComponent = this.target;
var inputValue = traitModel.get('value');
this.target.set('content', this.model.get('value'));
selectedComponent.set('attributes', {class: inputValue});
}
Which results in an HTML output of:
<input class="input txt-red" class="col-lg-6"/>
Obviously, this isn't legal HTML. It also produces weird results when adding or removing a class in the Classes input.
What is the correct way to go about this?
Answers (3)
@artf Is this even possible?
So I got this figured out, in a quite hacky way, but it works!
Just create a custom trait, and use the following for the onValueChange()
onValueChange() {
var parentModel = this.target.collection.parent.sm;
var component = this.target;
const sm = parentModel.get('SelectorManager');
var traitModel = this.model;
var selectedComponent = this.target;
var label = traitModel.get('value');
var compCls = component.get('classes');
compCls.forEach(element => {
if (element.id == this.model._previousAttributes.value) {
compCls.remove(element);
}
});
if (label) {
var classModel = sm.add({label});
compCls.add(classModel);
parentModel.trigger('targetClassAdded');
}
}
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Related Questions and Answers
Continue research with similar issue discussions.
Issue #1424
Checkbox trait value is rendered differently in view (render()) vs model (getHtml())
I have a custom component with a checkbox trait 'show-name'. When the trait value is 'true', the component renders in the view to the attri...
Issue #1894
[BUG] Custom Trait documentation example doesn't work
Specifically this: https://grapesjs.com/docs/modules/Traits.html#define-new-trait-type First of all, the keyUp event references onChange wh...
Issue #1586
[Question] update Trait select option dynamically
I tried this to update trait selection. var updateTrait = function(id, name) { var typeTrait = model.get('traits').where({name: 'type'})[0]...
Issue #1568
List/Array Trait
Hello, I am trying to write up a trait that allows creating a list of forms and generates the respective in the model. So far I have this:...
Paid Plugins That Match This Issue
Curated by issue keywords and label relevance to help you ship faster.
Loading paid plugin recommendations...
Check the open-source GrapesJS plugins on GitHub or run a quick search in our free catalog.
Browse free plugins →Premium plugins ship with support, regular updates, and production-ready features — save days of integration work.
Browse premium plugins →Related tutorials
In-depth guides on the same topic.
Browse Plugin Categories
Jump directly to plugin category pages on the marketplace.