I'm trying to use VueJs conditional rendering using handlebars in vueJs 2.0 as per their documentation but eslint is coming back with and error:
- avoid using JavaScript keyword as property name: "if" in expression {{#if ok}}
- avoid using JavaScript keyword as property name: "if" in expression {{/if}}
VueJs does not seem to be rendering it.
<!-- Handlebars template -->
{{#if ok}}
<h1>Yes</h1>
{{/if}}
If you are trying to use Vue.js syntax, the documentation outlines just a few lines down what's done for Vue.js. You would use the v-if directive.
<h1 v-if="ok">Yes</h1>
If like you mentioned, you're wanting to use Handlebars alongside Vue.js, note that both of them use the same {{ curly braces in templates. You may need to change Vue's use of the curly braces like so...
Vue.config.delimiters = ['<%', '%>'];
Either:
Using v-if to conditionally render
<h1 v-if="isVisible"> Yes </h1>
or using v-show to add a hidden attribute to that element style
<h1 v-show="isVisible"> Yes </h1>
either can be used but be careful with v-if since the element won't be in the DOM if the condition is not met.
I believe that is simply to document that the conditional does not go on a parent tag, but rather it is placed directly on the node that you want to conditionally display.
In other words its simply a comparison not part of Vue.js markup, but rather part of Handlebars.
Vue conditional rendering syntax
<h1 v-if="ok">Yes</h1>
<h1 v-show="ok">Yes</h1>
Details in original docs.
https://v2.vuejs.org/v2/guide/conditional.html#v-if-vs-v-show
Firstly, You should look at the vue documentation .https://v2.vuejs.org/v2/guide/conditional.html#v-if-vs-v-showjs and by the way, you can use "v-if" and "v-show"attributes, in flowing related to
examples.
<h1 v-if='isShow'>Test</h1>
<h1 v-show='isShow'>Test</h1>
For anyone coming here from a search trying to conditionally render inside {{ }} braces, you could always use a computed property:
import { computed } from 'vue';
<script setup>
const submitButtonText = computed(() => {
return props.formObject ? 'Save' : 'Create';
});
</script>
<template>
<form>
<button type="submit">
{{ submitButtonText }}
</button>
</form>
</template>
v-if and v-if-else work perfect for large elements, but this is great for simple one-line conditional text.
Related
Let's say we have the following HTML template:
<template id="my_template">
<div>
<h4>Test Titel</h4>
<div class="row">
<label for="someinput">Stichwort:</label>
<input id="someinput" type="text"/>
</div>
</div>
</template>
Now I like to render a list with multiple items based on that template.
I know that we can just clone the template and use selectors on it as on a regular DOM.
But is there also an alternative way to clone, etc... but with data, so that we can set the content without using selectors, but variables?
Something like the following, we just declare the variable ID before adding the template?
<template id="my_template">
<div>
<h4>Test Titel</h4>
<div class="row">
<label for="someinput_${ID}">Stichwort:</label>
<input id="someinput_${ID}" type="text"/>
</div>
</div>
</template>
I know it is possible with template literals, but I am just curious if this also works in any way with theses handy template tags?
Is it at all possible to set data in a temple tag without using selectors on it?
Is it at all possible to set data in a temple tag without using sectors on it ?
No, not in the way you mean. (The literal answer to the question quoted above is "yes" but only because you can modify the DOM without using selectors, per se — by doing the DOM traversal yourself. Not a useful "yes." 🙂 )
HTML template tags don't have an "evaluate with these variables" method or similar. As you've said in the question, you could always write a function that uses a JavaScript template literal to build the HTML instead (and then use insertAdjacentHTML() or innerHTML to add it to the DOM).
I am using an Angular Wrapper for JSON Editor like this:
<div *ngFor="let act of editedActions" class="w-100-p p-24">
{{act.test_step_id}}
<json-editor [options]="editorOptions" [(data)]="act.action_json" [(eventParams)]="act.test_step_id" (jsonChange)="changeStepActions($event)"></json-editor>
<button mat-raised-button class="w-100-p mt-24" color="primary" (click)="editRecordJson(act.test_step_id)">
<span>Update</span>
</button>
</div>
The problem is that eventParams should be different for each editor but it is not varying.
I think problem is this component code (but not sure) (This line is in the component taken from github):
#ViewChild('jsonEditorContainer', { static: true }) jsonEditorContainer: ElementRef;
The component is behaving like a singleton. Any help?
Edit: I edited this repo and added jsonchange event. Details here
You may want to use #ViewChildren with a direct reference to the component instead of a template variable string, to get all the JSON editors references:
#ViewChildren(JsonEditorComponent) jsonEditorContainers: QueryList<ElementRef>;
// ...
jsonEditorContainers.find(...);
It returns a QueryList that allows you to iterate through all ElementRef, and monitor the changes with an Observable changes.
What is eventParams? What is jsonChange? I could be wrong, but data doesn't seem to be two way bindable either, according to the source code.
It seems like you might be looking for something like this:
<div *ngFor="let act of editedActions" class="w-100-p p-24">
<json-editor [options]="editorOptions"
[data]="act.action_json"
(change)="changeStepActions($event, act.test_step_id)">
</json-editor>
</div>
You can then read the test_step_id in your changeStepActions method. If this works, I don't know how you made it compile in the first place.. are you using a CUSTOM_ELEMENTS_SCHEMA?
Its not necessary to use #ViewChildren for that you have to rewrite the entire code of component, make sure while using #ViewChild you pass correct editor reference.
As following
#ViewChild('carEditor' ) carEditor: JsonEditorComponent;
#ViewChild('mobileEditor') mobileEditor: JsonEditorComponent;
Stackblitz example for refernce :
Click here for code example
To use multiple jsoneditors in your view you cannot use the same editor options.
You should have something like:
<div *ngFor="let prd of data.products" class="w-100-p p-24" >
<json-editor [options]="makeOptions()" [data]="prd" (change)="showJson($event)"></json-editor>
</div>
makeOptions = () => {
return new JsonEditorOptions();
}
I'm using VueJS 2.0
Is there any way to make the below render as a link?
Here is my vue component:
<template>
<div v-html="markup"></div>
</template>
<script>
new Vue({
data() {
return {
markup: '<router-link :to="{path: 'https://www.google.com'}"></router-link>',
});
},
});
</script>
In the above example, I want to dynamically export a piece of markup, it contains some dynamic contents, such as router-link like above.
But that content did not compile, and exports a <router-link> tag as a final result.
Any way to make it compile programmatically?
What I really want is to find a way to compile a piece of html manually. If v-html doesn`t work, Is there any other way?
v-html works only for pre-compiled html which is basically generated text.
If you want do dynamically change content, simply use if conditions to render your list view based on prop that will tell you the type of the list view.
I don't think it's a good idea to save the markup in your db. It's rather more convenient to save some settings in your db and based on those to render the necessary html. (the prop type in your case). Maybe if you provide a more concrete example, some suggestions will follow. As you can see, the answers were based on your router-link example which I think is not enough to answer your question
I don't think you can instantiate Vue instances via v-html directive. You must override the default to do that, which would take lots of efforts.
If you just want dynamic links, why not try this:
data: {
menu: []
}
and then :
<router-link v-for="item in menu" :to="item.src">{{item.name}}</router-link>
PS: Can you give an example that you must do such things? I am really interesting in what needs it would be.
Given that you want to render a list of links, one way to do this can be like this:
<template>
<router-link v-for="list in lists" :to="{path: list}"></router-link>
</template>
<script>
new Vue({
data() {
return {
lists: ['https://www.google.com', 'https://www.stackoverflow.com']
});
},
});
</script>
Edit:
You can use an approach like following as well using with the help of dynamic components.
Vue.use(VueRouter)
new Vue({
el: "#app",
data: {
dynamicComp: "router-link"
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/2.2.0/vue-router.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.js"></script>
<div id="app">
somethind
<component :is="dynamicComp" :to="{path: 'https://www.google.com'}"></component>
</div>
Update
Apparently when using <template> the reading of innerHTML will return all attributes in lower case. Angular2 will not understand ngfor or ngif as of this beta 9 version and throws error. <script> is treated as a text fragment rather than DOM, which means attributes stay as they are.
Here:
https://groups.google.com/forum/#!topic/angular/yz-XdYV2vYw
Originial
Taking the following html and angular2 beta 9 component:
HTML CODE
<my-page>Loading...</my-page>
<script type="text/html" id="my-component-template1">
<select [(ngModel)]="SelectedType">
<option *ngFor="#someType of MyTypes" [selected]="SelectedType == someType" [value]="someType">{{someType}}</option>
</select>
</script>
<template id="my-component-template2">
<select [(ngModel)]="SelectedType">
<option *ngFor="#someType of MyTypes" [selected]="SelectedType == someType" [value]="someType">{{someType}}</option>
</select>
</template>
JS CODE
var myComponent =
ng.core.Component({
selector: 'my-page',
//complains if i use #my-component-template2
template: document.querySelector('#my-component-template1').innerHTML
})
.Class({
constructor: function () {
var self = this;
self.MyTypes = ['first', 'second'];
self.SelectedType = self.MyTypes[0];
}
});
document.addEventListener('DOMContentLoaded', function () {
ng.platform.browser.bootstrap(myComponent);
});
If i use my-component-template1 it works fine, but if i choose my-component-template2 it complains that ngModel and ngForOf are not a known native properties.
I tested a div as a template and apparently that won't work either with the same errors. So question is, why is it breaking if the template is part of the DOM? Furthermore, I really don't want to use the script text/html hack. Assuming this is why <template> was added in html5 specification. Why is this happening and how can i fix it?
The <template> tag is only used by Angular 2 structural directives (like the built-in ngIf, ngFor, ngSwitch, etc) - its use is somehow similar with the html5 specification since it defines content which is stored for subsequent use.
The * in front of a structural directive is just syntactic sugar which allows us to skip the <template> tag and focus directly on the HTML element that we are including, excluding, or repeating - you can read more about it here.
An example from Angular 2 docs which showcases this:
<!-- Examples (A) and (B) are the same -->
<!-- (A) *ngIf paragraph -->
<p *ngIf="condition">
Our heroes are true!
</p>
<!-- (B) [ngIf] with template -->
<template [ngIf]="condition">
<p>
Our heroes are true!
</p>
</template>
At the moment, I'm not sure if there's a way of defining inline Angular 2 HTML templates like there's in AngularJS 1. Your hack, as you put it, seems to do its job.
Angular handles <template> tags itself and doesn't simply add them to the DOM. If you inject TemplateRef into the constructor of your component you should get a reference to the template.
class MyComponent {
constructor(private tmplRef:TemplateRef) {
}
}
I am converting someone else's code to Handlebars.js and I'm stuck on converting this tag to its {{#handle-bar}}{{/handle-bar}} counterpart.
The previous coder used an {{#ifCond}} to toggle what 'selected'. This is my component.
{{#dropdown-item }}
{{unbound this.itemName}}
{{/dropdown-item}}
Here is the div i want converted to my component
<div class="dropdownItem" {{bind-attr value=formField_DropdownItemID}}{{#ifCond formField_DropdownItemID value}} selected{{/ifCond}} >
{{unbound this.itemName}}
</div>
My first thought was to just pop the div's logic into the the component, like the next example, but this gave me an error.
{{#dropdown-item bind-attr value=formField_DropdownItemID {{#ifCond formField_DropdownItemID value}} selected{{/ifCond}} }}
{{unbound this.itemName}}
{{/dropdown-item}}
Any suggestions?
You can set those properties to compute. The syntax would be:
{{#dropdown-item selected=computedProperty value=formField_DropdownItemID}}
computedProperty can deal with your conditional logic. The whole idea is to pull that out of handlebars anyways. :)