Reputation: 316
I want to manipulate the text inside the paragraph and get it's context to the component where I can manipulate it. Basically I want to do this:
<p bind="text"> Some text here </p>
export class Example{
@bindable text;
constructor()
{
this.Function()
}
Function() {
console.log(text)
//Here i want to be printed out Some text here
}
}
I don't mind if the answer will be written in jQuery or in JavaScript.
Upvotes: 0
Views: 723
Reputation: 897
I recommend to consider using custom attribute, or manipulating using ref
- but still it may be bad practice (JQuery/Angular way) of manipulating DOM directly.
ref
attribute to access element within VM class.MybindCustomAttribute
to define custom attribute mybind
and write it in mybind.js
file. Then the content of the attribute is achievable via valueChanged()
method. Do not use bind
as attribute name - as it can be confusing.app.html:
<template>
<require from='./mybind'></require>
<p ref="myparagraph" mybind="Add other text. ">Some text here. </p>
</template>
app.js, note that manipulateContent() adds some content within your the component:
export class App {
constructor() { }
attached() {
this.mytext = this.myparagraph.innerHTML;
this.manipulatecontent();
}
manipulatecontent() {
this.mytext += 'Hello world.';
this.myparagraph.innerHTML=this.mytext
}
}
mybind.js, with custom attribute class per Aurelia convention. You access the value of the attribute in valueChanged() method:
export class MybindCustomAttribute {
static inject = [Element];
constructor(element){
this.element = element;
}
valueChanged(newValue, oldValue){
this.element.innerHTML += newValue;
}
}
Fiddle it with GistRun at https://gist.run/?id=b712431087519a20d1a29c88906b7fe9
Upvotes: 0
Reputation: 5826
This answer is not correct, even though it's working. See accepted answer for better integration and explanation.
I've never worked with aurelia before, but looking at the documentation, this should do the trick:
Template:
<template>
<p ref="myParagraph" innerhtml.bind="text"></p>
</template>
Component:
export class ExampleComponent {
text = 'Example text';
constructor() {
this.exampleFunction();
}
exampleFunction () {
console.log(text);
// text should be here
}
}
If you need to read the text first (it's already set somewhere else, not in the component), you might need to read the value in the constructor.
constructor() {
this.text = this.myParagraph.innerHTML;
}
Upvotes: 0
Reputation: 14094
the accepted answer is really NOT the way to go. you should just do:
<template>
<p>${text}</p>
</template>
innerhtml
without sanitization is dengarous.DOM
inside the VM
is contradictive to the MVVM
paradigm.Upvotes: 2